JavaScript单选按钮确认

JavaScript radio button confirmation

本文关键字:确认 单选按钮 JavaScript      更新时间:2023-09-26

我正在尝试向现有函数添加一个函数或其他JavaScript以进行确认。点击提交按钮后,我需要一个确认框,上面写着:"你已经选择了(GCSE、A2或AS),这是正确的吗?"应该有一个取消按钮返回到表格,或者有一个OK按钮可以提交表格。

这是代码,我做了一点研究,它说使用循环,我对此非常陌生,所以我不知道该怎么办。

<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(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>

这样设置单选按钮的值:

<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:中调用它

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?');
}
add this to your code#
    function confirmation() {
    for (var i=0; i < document.ExamEntry.examtype.length; i++)
       {
       if (document.ExamEntry.examtype[i].checked)
          {
            var answer = confirm(document.ExamEntry.examtype[i].value)
        if (answer){
            document.ExamEntry.examtype[i].checked = true;
        }
        else{
            document.ExamEntry.examtype[i].checked = false;
        }
          }
    }
    }

然后添加到您的单选按钮的

( value="a2" )
( value="a1" )
( value="G1" )

还可以添加到单选按钮中(onclick="return confirmation();")记得把这个放在你们所有的单选按钮里如果这不起作用的话。