check a checkbox with a regex

Go To StackoverFlow.com

1

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.

2009-06-16 09:41
by sanders
... your reasoning makes no sense. There's nothing for a regular expression to match here. Checkboxes have a checked property. You look at that to see if they are checked. Where does a regex come in - Paolo Bergantino 2009-06-16 09:48
How would I program my computer with a fork - Galwegian 2009-06-16 09:50


3

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.");
}
2009-06-16 09:44
by Noldorin
i updated my pos - sanders 2009-06-16 09:47
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 2009-06-16 09:49


1

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

2009-06-16 09:43
by Greg
i updated my pos - sanders 2009-06-16 09:48


0

/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.

2009-06-16 09:49
by Matthew Flaschen


0

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

element.checked.toString().match(/true/)
2009-06-16 10:00
by Alsciende


0

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 :)

2009-06-16 10:01
by Dan F
Ads