3

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?

Community
  • 1
  • 1
Hommer Smith
  • 26,772
  • 56
  • 167
  • 296

4 Answers4

6

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.

Community
  • 1
  • 1
Cᴏʀʏ
  • 105,112
  • 20
  • 162
  • 194
  • So, you can't use the value attribute to decide. It's value is the same whether is checked or not. You always have to check if is checked or not. Right? – Hommer Smith Nov 02 '12 at 11:24
  • @HommerSmith: Unfortunately the `value` attribute behaves differently in various browsers as to whether form submitting includes the value whether it is checked or not. I made an edit that shows the "MVC" way -- a sort of fool-proof method to know whether a checkbox was really checked. – Cᴏʀʏ Nov 02 '12 at 11:26
1

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.

Shurmajee
  • 1,027
  • 3
  • 12
  • 35
0
$('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.

Abhilash
  • 1,610
  • 9
  • 19
0

check is the property of checkbox tag, so u have to check if it is set, no other value.

Mansoor Jafar
  • 1,458
  • 3
  • 15
  • 31