如何让单选按钮设置具有相同的ID?
我问的原因是我正在制作一个使用单选按钮的表单,但每个问题都是必需的。使用JS,我这样做是有效的。
这是我的代码:
<form>
<label>First name:</label>
<input type="text" id="fname"> <br><br>
<label>Last name:</label>
<input type="text" id="lname"> <br><br>
<label>Email address:</label>
<input type="text" id="email"> <br><br>
<label>Age</label>
<input type="text" id="age"> <br><br>
<label>Gender:</label><br>
<!-- radio button *help* -->
<input type="radio"> Male<br>
<input type="radio"> Female<br>
<input type="radio"> Other <br><br>
<!-- radio button *help* -->
<input type="submit" id="submit" value="Submit">
<input type="reset" name="reset" value="Reset">
</form>
JS:
var $ = function ( id ) { return document.getElementById( id ); }
var check = function()
{
var first = $("fname").value;
var last = $("lname").value;
var email = $("email").value;
var comments = $("comments").value;
var errors = "";
if ( first == "" )
errors += "You must enter a first name \n";
if ( last == "" )
errors += "You must enter a last name \n";
if ( email == "" )
errors += "You must enter an email address \n";
if ( errors == "" )
alert( "Thank you" );
else
alert( errors );
}
window.onload = function()
{
$("submit").onclick = check;
}
请注意,我在2周前开始使用JS,所以任何帮助都很有用!
谢谢!
答案 0 :(得分:0)
HTML中的ID必须是唯一的。您可以将required
添加到您的无线电元素,以便至少选择具有相同名称组的那个。
<form>
<input type="radio" name="gender" required /> Male<br />
<input type="radio" name="gender" required /> Female<br />
<input type="submit" />
</form>
&#13;