Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to make unchecked check box return a value with jQuery serialize?

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.

like image 590
jeffery_the_wind Avatar asked Apr 26 '12 19:04

jeffery_the_wind


1 Answers

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());
    });
});
like image 119
ScottE Avatar answered Oct 10 '22 02:10

ScottE