Omit empty strings from serializeArray in javascript

后端 未结 2 458
忘掉有多难
忘掉有多难 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

提交回复
热议问题