JavaScript 单选按钮确认单选、按钮、JavaScript

2023-09-06 19:06:27 作者:唱真声的男人

我正在尝试向现有函数添加一个函数或附加 JavaScript 以进行确认.单击提交按钮后,我将需要一个确认框,上面写着您选择了(GCSE、A2 或 AS),这是正确的吗?"应该有一个取消按钮来返回表单或一个允许提交表单的 OK.

I am trying to add a function, or additional JavaScript to the existing function for a confirmation. I will need a confirmation box once the submit button is clicked saying, "You have chosen (either GCSE, A2 or AS), is this correct?" There should be a cancel button to return to the form or an OK which lets the form be submitted.

这是代码,我做了一些研究,上面说使用循环,我对此很陌生,所以我不知道该怎么做.

Here is the code, I did a little research and it said use a loop, I am very new to this so I don't know what to do.

<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 
";
document.ExamEntry.name.focus();
document.getElementById('name').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>
<td id="name">Name</td>
<td><input type="text" name="name" /></td>
<tr>
<td id="subject">Subject</td>
<td><input type="text" name="subject" /></td>
</tr>
<tr>
<td id="examnumber">Examination Number</td>
<td><input type="text" name="examnumber" /></td>
</tr>
<tr>
<td><input type="radio" id="examtype" name="examtype" /> : GCSE<br />
<td><input type="radio" id="examtype" name="examtype"  /> : A2<br />
<td><input type="radio" id="examtype" name="examtype" /> : AS<br />
</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>

推荐答案

像这样设置单选按钮的值:

Set your radio buttons' values like this:

<td><input type="radio" id="examtype" name="examtype" value="GCSE" /> : GCSE<br />
<td><input type="radio" id="examtype" name="examtype" value="A2" /> : A2<br />
<td><input type="radio" id="examtype" name="examtype" value="AS"/> : AS<br />

然后在您的函数中使用此脚本来验证表单或使其成为一个函数并从您的函数 validateForm 中调用它:

Then use this script in your function to validate form or make it a function and call it from your function validateForm:

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?');
}