我创建了一个 HTML 多项选择题。我面临如何验证它的问题。下面是 HTML 代码:
<h1>JavaScript is ______ Language.</h1><br>
<form>
<input type="radio" name="choice" value="Scripting"> Scripting
<input type="radio" name="choice" value="Programming"> Programming
<input type="radio" name="choice" value="Application"> Application
<input type="radio" name="choice" value="None of These"> None of These
</form>
<button>Submit Answer</button>
当用户单击提交按钮时,应该有一个警报,根据所选内容显示一条消息。
- 如果未选择任何选项,则警告框应显示
“请选择选项答案”
。 - 如果选择“脚本”选项,则警告框应显示
“答案正确!”
- 如果选择了与“脚本”不同的选项,则警告框应显示
“答案错误”
。
我想在 JavaScript 中创建此验证。
最佳答案
你必须使用onclick属性和更多js
- 将事件处理程序附加到您的按钮
- 获取单选元素值
- 比较
var submitAnswer = function() {
var radios = document.getElementsByName('choice');
var val= "";
for (var i = 0, length = radios.length; i < length; i++) {
if (radios[i].checked) {
val = radios[i].value;
break;
}
}
if (val == "" ) {
alert('please select choice answer');
} else if ( val == "Scripting" ) {
alert('Answer is correct !');
} else {
alert('Answer is wrong');
}
};
<h1>JavaScript is ______ Language.</h1><br>
<form >
<input type="radio" name="choice" value="Scripting"> Scripting
<input type="radio" name="choice" value="Programming"> Programming
<input type="radio" name="choice" value="Application"> Application
<input type="radio" name="choice" value="None of These"> None of These
</form>
<button onclick="submitAnswer()">Submit Answer</button>
关于javascript - 在 javascript 中创建多项选择选项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34084048/