【发布时间】:2014-06-18 12:20:20
【问题描述】:
我正在处理一个 HTML 文档,它是一个考试提交表单。我已经完成了几乎所有设置的任务,但是,我在验证单选按钮时遇到了问题。我在stackoverflow上进行了搜索,但是答案不符合问题的标准。我完成的代码如下所示。
我在这个任务的粗体部分遇到问题:
在表单中添加一组单选按钮以接受某个级别的条目,例如 GCSE、AS 或 A2。 编写一个函数,在警告框中向用户显示进入级别,以便可以确认或拒绝该级别。
以下是工作代码,不包括单选按钮的验证。 Seperatley,我的代码在实现到函数 validateForm() 时不起作用。
<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.examno.value == "") {
msg += "You must enter your Examination Number \n";
document.ExamEntry.examno.focus();
document.getElementById('examinationno').style.color = "red";
result = false;
}
if (document.ExamEntry.examno.value.length!== 4) {
msg+="Your Examination Number should be 4 digits.\n";
document.ExamEntry.examno.focus();
document.getElementById('examinationno').style.color="red";
result = false;
}
if(msg==""){
return result;
}
{
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></tr>
<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="examinationno">Examination Number</td>
<td>
<input type="text" name="examno" />
</td>
</tr>
<tr>
<td>
<input type="radio" name="examtype" value="GCSE" />GCSE</td>
</tr>
<tr>
<td>
<input type="radio" name="examtype" value="AS" />AS</td>
</tr>
<tr>
<td>
<input type="radio" 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>
基于目前的代码,为什么添加到函数中时不会验证?:
if(document.getElementById('GCSE').checked)
{examtype = "GCSE";
}
if(document.getElementById('AS').checked)
{examtype = "AS";
}
if(document.getElementById('A2').checked)
{examtype = "A2";
}
if(confirm("You have selected"+examtype+.Continue?")){
if(msg==""){
return result;
}
{
alert(msg)
return result;
}
}
else{
alert("Action cancelled");
return false;
}
【问题讨论】:
-
这是一道作业题吗?此外,SO 突出显示的确认消息中存在错误。
-
这不是一个家庭作业问题,它是一项研究任务,其中互联网使用是必不可少的。确认消息有什么错误?我也不熟悉'SO'?感谢您的回复。
-
我不确定在 Javascript 中从哪里获得“互联网使用必不可少的研究任务”,但这个任务看起来很像一个家庭作业问题。有了这个,我看到你是一个新用户,所以我没有任何迹象表明这是或不是一个家庭作业问题。所以,我将简单地指出错误在哪里,并希望你能弄清楚。查看
if (confirm...) {并注意文本的颜色。然后看引号。 -
验证应该监听表单的峰会处理程序,而不是提交按钮的点击处理程序,因为可以在不点击按钮的情况下提交表单。
标签: javascript html function validation radio-button