0
我有一些代码,我一直有一些问题。出于某种原因,它会在检查文本字段之前检查单选按钮是否被选中。但是,我需要它是相反的。我是新来的Javascript,所以任何帮助,将不胜感激。这里是我的代码:Javascript表单验证 - 错误的订单
<html>
<head>
<title>Exam entry</title>
<script language="javascript" type="text/javascript">
function validateForm(){
var result = true;
var msg="";
if (document.ExamEntry.name.value==""){
msg+="You must enter your name \n";
document.ExamEntry.name.focus();
document.getElementById('name').style.color="red";
result = false;
}
if (document.ExamEntry.subject.value==""){
msg+="You must enter the subject \n";
document.ExamEntry.subject.focus();
document.getElementById('subject').style.color="red";
result = false;
}
if (document.ExamEntry.number.value.length!="4") {
msg+="You must enter your exam number and it must be 4 digits long \n";
document.ExamEntry.number.focus();
document.getElementById('number').style.color="red";
result = false;
}
var checked = null;
var inputs = document.getElementsByName('examtype');
for (var i = 0; i < inputs.length; i++) {
if (inputs[i].checked) {
checked = inputs[i];
break;
}
}
if(checked==null)
{
alert('Please choose an option');
return false;
}
else{
return confirm('You have chosen '+checked.value+' is this correct?');
}
if(msg==""){
return result;
}
else {
alert(msg);
return result;
}
}
</script>
</head>
<body>
<h1>Exam Entry Form</h1>
<form name="ExamEntry" method="post" action="success.html">
<table width="50%" border="0">
<tr>
<td id="name">Name</td>
<td><input type="text" name="name" /></td>
</tr>
<tr>
<td id="subject">Subject</td>
<td><input type="text" name="subject" /></td>
</tr>
<tr>
<td id="number">Exam Number</td>
<td><input type="text" name="number" /></td>
</tr>
<tr>
<td><input type="radio" id="examtype" name="examtype" value="GCSE">GCSE<br></td>
<td><input type="radio" id="examtype" name="examtype" value="AS">AS<br></td>
<td><input type="radio" id="examtype" name="examtype" value="A2">A2</td>
</tr>
<tr>
<td><input type="submit" name="Submit" value="Submit"
onclick="return validateForm();" /></td>
<td><input type="reset" name="Reset" value="Reset" /></td>
</tr>
</table>
</form>
</body>
</html>
如果我没有这段代码
var checked = null;
var inputs = document.getElementsByName('examtype');
for (var i = 0; i < inputs.length; i++) {
if (inputs[i].checked) {
checked = inputs[i];
break;
}
}
if(checked==null)
{
alert('Please choose an option');
return false;
}
else{
return confirm('You have chosen '+checked.value+' is this correct?');
}
然后正常工作。
任何帮助是很大的:)
如果我只选择1个单选按钮,然后按确定,即使我没有在文本字段中输入任何内容,它仍会继续。 –
正如@Amit Agarwal试图回答你的问题。我只是想让你知道一个标准。 '元素不能共享一个ID。它会导致意想不到的行为,特别是在使用javascript时。“您的单选按钮具有相同的ID。请检查;) –
我很抱歉,但我很新,我不知道你的意思是什么......哦,谢谢你艾米特它现在的作品! :) –