检查是否至少选择了一个单选按钮 - JavaScript [英] checking if at least one radio button has been selected - JavaScript
本文介绍了检查是否至少选择了一个单选按钮 - JavaScript的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
假设我有以下 HTML
表格:
<html xmlns="http://www.w3.org/1999/xhtml">
<head><meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Choose</title>
</head>
<body>
<form method="post" enctype="application/x-www-form-urlencoded">
<h1>Choose</h1>
<p><input type="radio" name="choose" value="psychology"><font size="5" color="#0033CC">Instant Psychology</font><br>
<br>
<input type="radio" name="choose" value="geography"><font size="5" color="#CC0000">Instant Geography</font><br>
<br>
<input type="radio" name="choose" value="gastronomy"><font size="5" color="#660033">Instant Gastronomy</font><br>
<br>
<input type="submit" name="Submit" value="Go"></p>
</form>
</body><link rel="stylesheet" type="text/css" href="data:text/css,"></html>
如何编写 JavaScript
函数确保至少选择了一个无线电输入?
How can I write a JavaScript
function to make sure at least one radio input has been selected?
推荐答案
循环< input>
标签,检查类型以及是否已选中。
Looping over the <input>
tags, check the type and if it is checked.
function isOneChecked() {
// All <input> tags...
var chx = document.getElementsByTagName('input');
for (var i=0; i<chx.length; i++) {
// If you have more than one radio group, also check the name attribute
// for the one you want as in && chx[i].name == 'choose'
// Return true from the function on first match of a checked item
if (chx[i].type == 'radio' && chx[i].checked) {
return true;
}
}
// End of the loop, return false
return false;
}
这篇关于检查是否至少选择了一个单选按钮 - JavaScript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文