How can I check whether a radio button is selected with JavaScript?(如何检查是否使用 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.
如果您只是想查看页面上的any单选按钮是否被选中anywhere,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 选择了单选按钮?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何检查是否使用 JavaScript 选择了单选按钮?


- CSS媒体查询(最大高度)不起作用,但为什么? 2022-01-01
- Css:将嵌套元素定位在父元素边界之外一点 2022-09-07
- 失败的 Canvas 360 jquery 插件 2022-01-01
- 使用RSelum从网站(报纸档案)中抓取多个网页 2022-09-06
- addEventListener 在 IE 11 中不起作用 2022-01-01
- Flexslider 箭头未正确显示 2022-01-01
- Quasar 2+Apollo:错误:找不到ID为默认的Apollo客户端。如果您在组件设置之外,请使用ProvideApolloClient() 2022-01-01
- 400或500级别的HTTP响应 2022-01-01
- Fetch API 如何获取响应体? 2022-01-01
- 如何使用 JSON 格式的 jQuery AJAX 从 .cfm 页面输出查 2022-01-01