如何检查是否使用JavaScript选择了一个单选按钮? [英] How can I check whether a radio button is selected with JavaScript?

查看:104
本文介绍了如何检查是否使用JavaScript选择了一个单选按钮?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在HTML表单中有两个单选按钮。当其中一个字段为空时,会出现一个对话框。如何检查是否选择了一个单选按钮?

I have two radio buttons within an HTML form. A dialog box appears when one of the fields is null. How can I check whether a radio button is selected?

推荐答案

让我们假装你有这样的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.

这篇关于如何检查是否使用JavaScript选择了一个单选按钮?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆