views:

196

answers:

6

What would be the correct regex to check wether a checkbox is checked in javascript?

update: i know it is usually not done with a regex. But since its part of a form module and all the validations are done with a regex. I thought this could also be checked with a regex. My quyestion is how.

+1  A: 

Regex? How about just looking at the .checked property?

Greg
i updated my post
sanders
+2  A: 

You really just want to access the checked property. (Truly, regex has no place here - it should be used only with lack of anything better.)

Try this:

var checkbox = document.getElementById("myCheckbox");
if (checkbox.checked)
{
    alert("Checkbox is CHECKED.");
}
else
{
    alert("Checkbox is UNCHECKED.");
}
Noldorin
i updated my post
sanders
I can't even think *how* regex could be used to check for this, let alone *should* be used. There's no problem with using multiple forms of validation. A simple boolean check is the right way to do it here.
Noldorin
A: 
/true/.test(document.getElementById("myCheck").checked.toString())

/You might want to look at the other answers too..., unless you like fishing with an ice cream scoop.

Matthew Flaschen
A: 

I know it's a bit cliche for stack overflow, but might I recommend using jquery? If so, then you can use the :checked selector.

if($("input#something").is(":checked")) {
    alert("Checked");
} else {
    alert("Not checked");
}
Kazar
May I ask what browser doesn't support the .checked property?
Paolo Bergantino
Kazar, care to tell us where it's not guaranteed? It's in the W3C spec (http://www.w3.org/TR/1998/REC-DOM-Level-1-19981001/ecma-script-language-binding.html) and it's been around since /at least/ IE4, Firefox 1, etc.
Matthew Flaschen
This is the jQuery code for the :checked selector = checked: function(elem){ return elem.checked === true; }, -- I'm going to go ahead and say it's supported everywhere...
Paolo Bergantino
My apologies, removed the claim about lack of support.
Kazar
Removed downvote. :)
Paolo Bergantino
The checked property been around since JavaScript first appeared in Netscape Navigator 2, back in 1996; if it isn't supported by a browser, neither is JavaScript nor DOM Level 0.
NickFitz
A: 

Well, if you have to do it this way, you can use a regexp on the checked property

element.checked.toString().match(/true/)
Alsciende
A: 

assuming that the library you are using checks the value property of the dom element, the following might help.

For a checkbox with value="foo", the .value property returns "foo" if it is checked and nothing (null?) if it isn't. So, the correct regular expression would be whatever means "at least one character". I'm no regular expression guru so I won't even attempt it :)

Dan F