When using serializeArray()
for a form with empty fields it returns \"\"
for all those fields. What is the best way to omit those empty fields from
If you don't want to filter resulting array, or want to apply requested behaviour to all forms in project, you can create jquery hook for form's property elements and filter form fields as you want. So serializeArray()
will see only the elements you allow it to see.
Just add this code somethere in your initialization section:
$.propHooks.elements = {
get: function(elem) {
var result = Array.prototype.slice.call(elem.elements);
result = result.filter(function(elem) {
//filtering out text fileds with empty value
return !(elem.type === 'text' || elem.type === 'textarea' || elem.type === 'hidden')
|| elem.value
});
return result;
}
};
jsFiddle example
Iteration is neccessary as serializeArray creates an array of objects, and each value has to be checked.
Using a filter seems appropriate :
$('form').serializeArray().filter(function(k) {
return $.trim(k.value) != "";
});
FIDDLE