sanders
sanders

Reputation: 10898

check a checkbox with a regex

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.

Upvotes: 2

Views: 7018

Answers (5)

Dan F
Dan F

Reputation: 12051

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

Upvotes: 0

Alsciende
Alsciende

Reputation: 26971

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

element.checked.toString().match(/true/)

Upvotes: 0

Matthew Flaschen
Matthew Flaschen

Reputation: 284947

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

Upvotes: 0

Noldorin
Noldorin

Reputation: 147441

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.");
}

Upvotes: 3

Greg
Greg

Reputation: 321786

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

Upvotes: 1

Related Questions