How can I serializeArray for unchecked checkboxes?

前端 未结 12 821
耶瑟儿~
耶瑟儿~ 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:27

    Yet Another SerializeArray()

    This implementation is again based on jQuery's original code, but I needed it for some Bootstrap's "switch" checkboxes with two different values.

    $.fn.serializeArrayWC = function() {
        var rCRLF = /\r?\n/g;
        return this.map(function(){
            return this.elements ? jQuery.makeArray( this.elements ) : this;
        })
        .map(function(i, elem){
            if (this.type == "checkbox") {
                // Bootstrap checkboxes with two different values.
                if (jQuery(this).hasClass("switched")) {
                    // Always return value (either on-value or off-value).
                    return { name: this.name, value: this.value };
                }
                // Normal checkboxes. Unchecked checkboxed are not returned.
                if (!this.checked) {
                    // This will be removed by the !!f filter, below.
                    return false;
                }
                // Return the value, or "on".
                return { name: this.name, value: this.value||"on" };
            }
            var val = jQuery(this).val();
            if (val == null) {
                return { name: elem.name, value: null };
            } 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" ) };
            }
        })
        .filter(function(i, f){ return !!f; })
        .get();
    };
    

提交回复
热议问题