且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何检查是否使用JavaScript选择了一个单选按钮?

更新时间:2023-11-29 10:22:04

让我们假装你有这样的HTML

Let's pretend you have HTML like this

<input type="radio" name="gender" id="gender_Male" value="Male" />
<input type="radio" name="gender" id="gender_Female" value="Female" />

对于客户端验证,这里有一些Javascript来检查选择了哪一个:

For client-side validation, here's some Javascript to check which one is selected:

if(document.getElementById('gender_Male').checked) {
  //Male radio button is checked
}else if(document.getElementById('gender_Female').checked) {
  //Female radio button is checked
}

根据标记的确切性质,上述内容可以更高效,但这应该足以让您入门。

The above could be made more efficient depending on the exact nature of your markup but that should be enough to get you started.

如果您只想查看页面上是否任何 任何单选按钮 PrototypeJS 让它变得非常简单。

If you're just looking to see if any radio button is selected anywhere on the page, PrototypeJS makes it very easy.

这个函数至少会返回true在页面的某处选择一个单选按钮。同样,这可能需要根据您的特定HTML进行调整。

Here's a function that will return true if at least one radio button is selected somewhere on the page. Again, this might need to be tweaked depending on your specific HTML.

function atLeastOneRadio() {
    return ($('input[type=radio]:checked').size() > 0);
}






用于服务器端验证(记住,你不能完全依赖Javascript进行验证!),这取决于你选择的语言,但是你要检查性别请求字符串的值。


For server-side validation (remember, you can't depend entirely on Javascript for validation!), it would depend on your language of choice, but you'd but checking the gender value of the request string.