33

Hi I have an html form which I am submitting via the click event on a button. The event fires $("#myform").submit(); the problem is that there is a checkbox on the form and in firebug under the posted params it shows "mycheckbox1 on" rather then the expected "mycheckbox1 true".

when submitting a form via ajax I can set the data that is posted no problem but this form has a file upload which requires one of the various hacks to make it work. The one I'm using ultimately calls submit. but perhaps that is not relevant.

In any case when the data arrives at the server, the server doesn't see the value "on" as a bool and thus ignores it.

Any insight would be greatly appreciated.

alex
  • 479,566
  • 201
  • 878
  • 984
Raif
  • 8,641
  • 13
  • 45
  • 56
  • 2
    What value does the checkbox have? If it has no `value` attribute, it can only report `on`. – jk. Feb 08 '12 at 00:00
  • 1
    Yes I've read this but strangely when I watch a checkbox with firebug and I check and uncheck it it doesn't show a value. Perhaps I need to set the value as false when the checkbox is created or maybe I need a global onChange event handler to manually handle setting the value. – Raif Feb 08 '12 at 13:54

3 Answers3

33

A checked checkbox simply sends its value attribute. An unchecked checkbox doesn't send itself in the form.

Therefore, a simple test if the checkbox's name attribute was posted can determine if it was checked or not.

alex
  • 479,566
  • 201
  • 878
  • 984
  • 1
    Did not know that unchecked checkboxes didn't get sent in POST... been trying to figure out a similar problem for over half an hour! +1 – Chris Cirefice Oct 22 '14 at 06:26
7

Yeah, different browsers might handle checkboxes differently when the value is not set.

You can set the value attribute of the checkbox explicitly to "true" as your server understands it when checkbox is checked and it gets sent to it. As Alex hinted in his answer, the checkbox wont be sent if it's unchecked, so, I assume the server will default to false in this case.

Meligy
  • 35,654
  • 11
  • 85
  • 109
  • I was having a similar problem with Play until I explicitly added `value="true"` to my checkbox. – Matthew Apr 25 '16 at 13:42
6

Try selecting or sending the checked value with the form:

$("input:checked").val()

http://jsfiddle.net/YxZRS/

jk.
  • 14,365
  • 4
  • 43
  • 58