How Can I Serializearray For Unchecked Checkboxes?
Solution 1:
It's probably easiest to just do it yourself:
var serialized = $('input:checkbox').map(function() {
return { name: this.name, value: this.checked ? this.value : "false" };
});
If there are other inputs, then you could serialize the form, and then find the unchecked checkboxes with something like the above and append that result to the first array.
Solution 2:
serializeArray
ignores the checkboxes which are not checked. You can try something like this.
Working demo
var serializedObj = {};
$("form input:checkbox").each(function(){
serializedObj[this.name] = this.checked;
});
Solution 3:
you can use this get unchecked values
$.fn.serializeObject = function () {
var o = {};
var a = this.serializeArray();
$.each(a, function () {
if (o[this.name] !== undefined) {
if (!o[this.name].push) {
o[this.name] = [o[this.name]];
}
o[this.name].push(this.value || '');
} else {
o[this.name] = this.value || '';
}
});
var $radio = $('input[type=radio],input[type=checkbox]',this);
$.each($radio,function(){
if(!o.hasOwnProperty(this.name)){
o[this.name] = '';
}
});
return o;
};
Solution 4:
Here's how I implemented a simple override of $.serializeArray
which fixes the default serialization behaviour for checkboxes, and default behaviour is retained for all other types.
In the code below, missed checkboxes are injected into the original serialized array. Checkbox state is returned as "true"
(instead of "on"
) or "false"
depending on if it is checked
or not.
(function ($) {
var _base_serializeArray = $.fn.serializeArray;
$.fn.serializeArray = function () {
var a = _base_serializeArray.apply(this);
$.each(this.find("input"), function (i, e) {
if (e.type == "checkbox") {
e.checked
? a[i].value = "true"
: a.splice(i, 0, { name: e.name, value: "false" })
}
});
return a;
};
})(jQuery);
You could customize this to return "on"/"off"
or true/false
.
Update: Fixed code based on bug found by @shyammakwana.me.
Solution 5:
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;
returnthis.map(function(){
returnthis.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 ){
varval = jQuery( this ).val();
returnval == 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();
};
Post a Comment for "How Can I Serializearray For Unchecked Checkboxes?"