最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - check a checkbox with a regex - Stack Overflow

programmeradmin5浏览0评论

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.

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.

Share Improve this question edited Jun 16, 2009 at 9:47 sanders asked Jun 16, 2009 at 9:41 sanderssanders 10.9k28 gold badges90 silver badges131 bronze badges 2
  • 5 ... 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 e in? – Paolo Bergantino Commented Jun 16, 2009 at 9:48
  • 5 How would I program my puter with a fork? – Galwegian Commented Jun 16, 2009 at 9:50
Add a ment  | 

5 Answers 5

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

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

发布评论

评论列表(0)

  1. 暂无评论