Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery form post converts boolean checkboxes to "on" and "off"?

I have a fairly simple form with a checkbox, and I noticed that my checkbox values weren't being picked up on my server side app:

$.post('CreateForm', $('#new-form').serialize(), ... 

Everything else posts correctly, but I'm seeing in Firebug that it'll serialize the checkbox value as "on" or "off" instead of "true" and "false" that I get with a normal <form method="post" action="formpage"> ... what's going on here, is this expected behavior? My server side model binder doesn't equate "on" with "true" and thus drops the value. Obviously I could change the model binder, but wanted to make sure I wasn't doing it wrong.

Edit:

Here's my markup:

<input type="checkbox" name="CheckboxValue" > 

jQuery version 1.4.4

In Firebug here's the resulting post:

... other variables &CheckboxValue=on 
like image 231
chum of chance Avatar asked Mar 15 '11 20:03

chum of chance


People also ask

How do you check checkbox is on or off in jQuery?

click(function() { var checkBoxes = $("input[name=recipients\\[\\]]"); checkBoxes. prop("checked", !

How can get Boolean value from checkbox in jQuery?

To check whether a Checkbox has been checked, in jQuery, you can simply select the element, get its underlying object, instead of the jQuery object ( [0] ) and use the built-in checked property: let isChecked = $('#takenBefore')[0]. checked console. log(isChecked);

How do I toggle checkbox value?

#Toggle Checkbox by Simulating a Mouse ClickBy using the click() method on the checkbox we can simulate a mouse click, which would flip the checkbox value. For example: checkbox. click();

How check toggle is checked or not in jQuery?

prop() and is() method are the two way by which we can check whether a checkbox is checked in jQuery or not.


2 Answers

The problem is that your checkboxes do not have value attributes. When jQuery serializes the form, it uses 'on' as the default value.

You should give your checkbox a value:

<input type="checkbox" name="CheckboxValue" value="true" /> 

See example here: http://jsfiddle.net/U6Sbw/1/

like image 192
Rocket Hazmat Avatar answered Sep 30 '22 09:09

Rocket Hazmat


A little late, but just in case someone stumbles across this: if you also want false values to be output, this jQuery plugin provides the option to always ignore the checkbox's "value" and instead serialize it as "true" or "false":

http://tdanemar.wordpress.com/2010/08/24/jquery-serialize-method-and-checkboxes/

like image 34
Tao Avatar answered Sep 30 '22 09:09

Tao