form submit checkbox sets value to “on” rather tha

2019-04-18 02:09发布

问题:

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.

回答1:

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.



回答2:

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.



回答3:

Try selecting or sending the checked value with the form:

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

http://jsfiddle.net/YxZRS/