我有一项计算任务要做。
我已经完成了大部分任务,但我只是停留在这个任务上:
"Add a set of radio buttons to the form to accept a level of entry such as
GCSE, AS or A2. Write a function that displays the level of entry to the user
in an alert box so that the level can be confirmed or rejected."
我已经完成了单选按钮,但我只是不知道如何使用警报框和功能来完成第二部分。
到目前为止,我的代码如下所示:
<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 (msg=="") {
return result;
}
{
alert(msg)
return result;
}
}
</script>
</head>
<! Main HTML content begins >
<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" maxlength="4" /></td>
</tr>
<tr>
<td><input type="radio" name="Level" value="GCSE">GCSE</td>
</tr>
<tr>
<td><input type="radio" name="Level" value="AS">AS</td>
</tr>
<tr>
<td><input type="radio" name="Level" 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>
最佳答案
您所要做的就是将单选按钮的值添加到消息中,如下所示:
msg += "Level of Entry: "+document.ExamEntry.Level.value;
Here is a fiddle demo you can try
编辑#1:虽然据说使用警报框,但实际上并不允许用户确认或拒绝,为此,您可以使用确认代替:
if (confirm("Click OK to confirm your Level of Entry or Cancel if you would like to correct it"))
return true;
else
return false;
在我的示例中,我仅在表单验证的其余部分成功的情况下添加它:http://jsfiddle.net/Qd8sk/2/
编辑#2:在我们的谈话之后,我更新了您创建的 jsfiddle。它比您提供的要简单得多。
这是你的:http://jsfiddle.net/Kjxmn/
这是我的:http://jsfiddle.net/Kjxmn/2/
我改变的几件事:
-1。在 onchange
中的函数名称前面添加了 return
- 看起来即使在 return false
上它仍然会提交。
-2。更正了您这次称为 radioform
的表单名称,而不是 Exam Entry
。
-3。使用 if (document.radioform.level.value == '')
摆脱了对所选值的稍微麻烦的检查。
-4。添加了确认检查。
编辑 #3: 看起来 Firefox 不喜欢对单选按钮使用 document.ExamEntry.Level.value
,因此我创建了一个快速解决方法将循环遍历 document.ExamEntry.Level
的元素并找到“选中”的元素(实际上是“选中” - 即使它是一个单选按钮,js 代码仍然称为“选中”) .
看看更新后的 fiddle :http://jsfiddle.net/Qd8sk/3/
关于javascript - 如何使用 JavaScript 函数验证单选按钮?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23346569/