4

I have form with several text inputs.

When user clicks submit on this form - text input field values being serialized and become parameters of GET request like this

?param1+=26482&param2=

I need to check: if parameter has no value then remove it. So only parameters with values will be appended to GET request.

How it should be done?

My submit function

$("body").on('click','#form_submit_button', function(e){
    var form = $('#filter_form');
    change_url('?'+form.serialize());
});

function change_url(link)
{
    var IE = IE || 0;

    if (IE == 0) {
        var stateObj = { foo: "bar" };
        history.pushState(stateObj, "page 2", link);
    } else {
        location.href = link;
    }
}

3 Answers 3

4

You can use the following js which filter your form including only inputs with a value.

http://jsfiddle.net/63ux5ap9/

  $(document).ready(function () {
        $('#filter_form').submit(function () {
            var text = $(this).find(":input").filter(function () {
                return $.trim(this.value).length > 0
            }).serialize();
            console.log('text: ', text);
            return false;
        });
    });
Sign up to request clarification or add additional context in comments.

3 Comments

+1 for submit event instead of click and use of :input (you forgot to include the jQuery lib in you fiddle)
"that works, but not as it should" What in the world does that mean?
@Brewal I have added jQuery lib. Thanks for reminding me :)
1

jQuery $.fn.serialize is a combination of $.param and $.fn.serializeArray methods:

jQuery.fn.serialize = function () {
    return jQuery.param(this.serializeArray());
}

It means that in order to achiever what you are after you can use the same approach and perform additional filtering of the resulting array returned by serializeArray:

var form = $('#filter_form'),
    params = $.param(form.serializeArray().filter(function(el) {
        return $.trim(el.value);
    }));

change_url('?' + params);

Comments

0

What do you need is:

var i = str.lastIndexOf("&");

So

if(str.length <= str.lastIndexOf("=")) {
   var i = str.lastIndexOf("&");
   str = str.substring(0, i); 
}

By the way, I would remove problem from radix!

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.