Hailwood
Hailwood

Reputation: 92601

How to tell whether a checkbox is checked?

As most people know there are at least two (easy) ways to findout if a checkbox is checked.

($('#checkbox:checked').val() != undefined) OR ($('#checkbox').val() == 'on')

Which of these two methods is best? why?

Upvotes: 2

Views: 984

Answers (3)

Lèse majesté
Lèse majesté

Reputation: 8045

If you're accessing the raw element, you should be able to use something like:

this.checked

But I don't know if there might be any cross-browser compatibility issues with this method.

Upvotes: 6

CrayonViolent
CrayonViolent

Reputation: 32532

Another way

if ($('#myCheckbox').attr("checked")) { .. }

Anyways...I don't think any one of these is necessarily better or worse. jQuery is designed to work across browsers so any one of them should work. Not sure anybody has taken the time to actually benchmark them for performance or anything...just do what you feel is most readable to you.

Upvotes: 2

Jan
Jan

Reputation: 2293

I think that

$('#checkbox').is(':checked');

is the way to go.

Upvotes: 6

Related Questions