我在 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 选择了单选按钮?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!