micgeronimo micgeronimo - 7 months ago 83
Javascript Question

Remove empty values before form submit jquery

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

Answer

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