How can I serializeArray for unchecked checkboxes?

前端 未结 12 861
耶瑟儿~
耶瑟儿~ 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条回答
  •  庸人自扰
    2021-02-05 08:36

    I made my own new solution based on the answers by @Pointy, @Ben, and the original jQuery code. The answer from @Pointy had odd behavior that returned contexts for checkboxes, this fixes that problem. The answer from @Ben was also not acting properly because it always returned checkbox = on even if it was unchecked.

    $.fn.serializeArrayWithCheckboxes = function() {
    var rCRLF = /\r?\n/g;
    return this.map(function(){
        return this.elements ? jQuery.makeArray( this.elements ) : this;
    })
    
        .map(function( i, elem ){
            var val = jQuery( this ).val();
    
    
            if (val == null) {
              return val == null
            //next 2 lines of code look if it is a checkbox and set the value to blank 
            //if it is unchecked
            } else if (this.type == "checkbox" && this.checked == false) {
              return { name: this.name, value: this.checked ? this.value : ""}
            //next lines are kept from default jQuery implementation and 
            //default to all checkboxes = on
            } else {
              return 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();
    };
    

提交回复
热议问题