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
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.
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;
};
code samples
you can add a hidden false value for every checkbox:
<input type="checkbox" name="Check01" value="true" /><input name="Check01" type="hidden" value="false" />
<input type="checkbox" name="Check02" value="true" checked="checked" /><input name="Check02" type="hidden" value="false" />
You will only get "false" values for unchecked checkboxes and both "true" and "false" for checked checkboxes, so you can remove the duplicates like this:
var params = {};
$.each($('form').serializeArray(), function (index, value) {
params[value.name] = params[value.name] ? params[value.name] || value.value : value.value;
});
console.log(params); // outputs: {"Check01":"false","Check02":"true"}
@SNag's answer worker almost 99% just with little bit correction. Change below line
$.each(this, function (i, e) {
$.each(this.find('input'), function (i, e) {
Explanation: As this was not working because this
returned form element. So on form .each
won't give us all input elements inside form. So I did this correction and it worked like charm.
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;
});
var fields = $("form").serializeArray();
$('form input[type=checkbox]').map(function() {
if( !this.checked )
{
fields.push({ name: this.name, value: "off" });
}
});