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¶m2=
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;
}
}
source to share
You can use the following js which will filter your form to include only value inputs.
$(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;
});
});
source to share
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);
source to share