Omit empty strings from serializeArray in javascript

后端 未结 2 454
忘掉有多难
忘掉有多难 2020-12-22 00:42

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

相关标签:
2条回答
  • 2020-12-22 01:08

    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

    0 讨论(0)
  • 2020-12-22 01:25

    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

    0 讨论(0)
提交回复
热议问题