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.
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.");
}
Regex? How about just looking at the .checked
property?
/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.
Well, if you have to do it this way, you can use a regexp on the checked property
element.checked.toString().match(/true/)
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 :)