Last active
March 27, 2019 11:42
-
-
Save alexandermitsyk/8f1ccff07f857e3bbc8a3fbe8fe899b2 to your computer and use it in GitHub Desktop.
jQuery form unchecked checkbox serialize script
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//source https://tdanemar.wordpress.com/2010/08/24/jquery-serialize-method-and-checkboxes/ | |
//added selector option | |
(function ($) { | |
$.fn.serialize = function (options) { | |
return $.param(this.serializeArray(options)); | |
}; | |
$.fn.serializeArray = function (options) { | |
var o = $.extend({ | |
checkboxesAsBools: false, | |
defaultselector: 'custom-sw' | |
}, options || {}); | |
var rselectTextarea = /select|textarea/i; | |
var rinput = /text|hidden|password|search/i; | |
return this.map(function () { | |
return this.elements ? $.makeArray(this.elements) : this; | |
}) | |
.filter(function () { | |
return this.name && !this.disabled && | |
(this.checked || | |
(o.checkboxesAsBools && this.type === 'checkbox' && $(this).hasClass(o.defaultselector)===true) || | |
rselectTextarea.test(this.nodeName) || | |
rinput.test(this.type)); | |
}) | |
.map(function (i, elem) { | |
var val = $(this).val(); | |
return val == null ? | |
null : | |
$.isArray(val) ? | |
$.map(val, function (val, i) { | |
return { | |
name: elem.name, | |
value: val | |
}; | |
}) : { | |
name: elem.name, | |
value: (o.checkboxesAsBools && this.type === 'checkbox' && $(this).hasClass(o.defaultselector)===true) ? //moar ternaries! | |
(this.checked ? 'true' : 'false') : val | |
}; | |
}).get(); | |
}; | |
})(jQuery); | |
$("#myform").serialize({ checkboxesAsBools: true, defaultselector: 'custom-checkbox'}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment