Remove empty values ​​before submitting jquery form

I have a form with multiple text inputs.

When the user clicks the submit button on this form - the values ​​of the text input field are serialized and become parameters of a GET request such as

?param1+=26482&param2=

      

I need to check: if the parameter is irrelevant, remove it. Thus, only parameters with values ​​will be added to the GET request.

How to do it?

My send 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


source to share


3 answers


You can use the following js which will filter your form to include only value inputs.

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;
        });
    });

      

+4


source


jQuery $.fn.serialize

is a combination of methods $.param

and $.fn.serializeArray

:

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

      



This means that in order to achieve what you are after, you can use the same approach and do some additional filtering on the resulting array returned serializeArray

:

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

change_url('?' + params);

      

+1


source


What you need:

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 the problem from radix!

0


source







All Articles