1

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 the Array besides iterating over the Array and deleting them one by one?

2 Answers 2

6

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

Sign up to request clarification or add additional context in comments.

1 Comment

THATS AMAZING! THANK YOU!
1

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

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.