Correct way of knowing if a checkbox is checked

Possible Duplicate:
Check if checkbox is checked with jQuery

I am a little bit confused about how the input of type checkbox works.

If I set a value, say 1, on a checkbox, I see that regardless of the checkbox is checked or not, the value that I get when the form is submitted is 1.

<input type="checkbox" value="1">

So, the correct way to see if a checkbox is checked is to use the checked from jQuery? Or how it can be done correctly?


Checkbox values should not get submitted if they are not checked.

If you want to check with jQuery, I would always use:

var isChecked = $('#checkbox').prop('checked');

Or

var isChecked = $('#checkbox').is(':checked');

With JavaScript, you have to understand the difference between attributes and properties. checked is both a property and an attribute. However, the attribute checked isn't always updated when the checked property of a checkbox changes (in some browsers it is). Think of the attribute as the value in the HTML markup parsed by the DOM. The checked property is an actual member of the checkbox element in the DOM, which always changes based on whether the box is checked or unchecked in the UI.

If you want to try a foolproof method without needed JavaScript, you can try it the "MVC" way, by rendering a hidden input and a checkbox with the same name, each with appropriate "checked"-state values:

<input type="hidden" name="mybox" value="false" />
<input type="checkbox" name="mybox" value="true" />

When you submit the form, if you can't find a mybox value in the request with a value of "true" then the checkbox was not checked. More about that here.


in order to check if the checkbox is actually checked you must use

'boxname.checked=="" 

as the value will always be there even if the box is not checked.


$('input[type=checkbox]').is(':checked')

This returns true if checked, and false if not.

In answer to your comment on the question, there is not much to be gained by the value when you need the checked state.

链接地址: http://www.djcxy.com/p/55980.html

上一篇: 检查提交时是否检查所有复选框

下一篇: 正确的方式知道是否选中了复选框