I have an HTML form with some checkboxes. I use jQuery .serialize()
function to make a query string to submit to the database. The problem I am having is that when a checkbox is unchecked, the .serialize()
function does not register it in the query string.
My problem is illustrated in this jsfiddle: http://jsfiddle.net/cTKhH/.
This is a problem because i still need to save a value of the unchecked check box to the database. Right now the information is only saved when the check box is checked. When it is unchecked, and the information from .serialize()
is submitted, no change is made since there is no information submitted.
Does anyone know how to make my .serialize()
function return the unchecked value for all check boxes when they are unchecked?
Thanks!!
** EDIT **
Just a little more info, I know now why the unchecked check box is not submitted, because it is not a "successful" form control, see here: http://www.w3.org/TR/html401/interact/forms.html#successful-controls.
Hopefully I still modify the .serialize()
function to submit unchecked values.
Here is a simple example - I'm sure you could wrap this into a nice plugin.
html
<form id="doit" action="" method="post">
<input type="checkbox" name="test" data-checkedName="test" data-uncheckedid="yup" value="true" class="checkedValue" />
<input type="hidden" name="test" id="yup" value="false" />
<input type="submit" value="serialize" />
</form>
js
$(function () {
$(".checkedValue").click(function () {
var $cb = $(this),
$associatedHiddenField = $("#" + $cb.attr("data-uncheckedid")),
name = $cb.attr("data-checkedName");
if (this.checked) {
$cb.attr("name", name);
$associatedHiddenField.removeAttr("name");
} else {
$cb.removeAttr("name");
$associatedHiddenField.attr("name", name);
}
});
$("#doit").submit(function (e) {
e.preventDefault();
console.log($(this).serialize());
});
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With