How can I serializeArray for unchecked checkboxes?

前端 未结 12 1032
耶瑟儿~
耶瑟儿~ 2021-02-05 08:01

How can I modify this example so it can get values from checkboxes that aren\'t checked?

I want all checkboxes to have a value, if it hasn\'t been checked I want to get

12条回答
  •  萌比男神i
    2021-02-05 08:29

    another option is to just look at the source code for serializeArray and remove (or modify) the call to filter. I Just took that function and created a new one called serializeArrayAll like this:

    $.fn.serializeArrayAll = function() {
      var rCRLF = /\r?\n/g;
      return this.map(function(){
          return this.elements ? jQuery.makeArray( this.elements ) : this;
      })
      /* this is what is excluding the unchecked checkboxes (and also other disabled options) 
          .filter(function(){
            return this.name && !this.disabled &&
                ( this.checked || rselectTextarea.test( this.nodeName ) ||
                    rinput.test( this.type ) );
        })
       */
      .map(function( i, elem ){
          var val = jQuery( this ).val();
    
          return val == null ?
              null :
              jQuery.isArray( val ) ?
                  jQuery.map( val, function( val, i ){
                      return { name: elem.name, value: val.replace( rCRLF, "\r\n" ) };
                  }) :
              { name: elem.name, value: val.replace( rCRLF, "\r\n" ) };
      }).get();
    };
    

提交回复
热议问题