gpt4 book ai didi

javascript - 在javascript中创建多项选择选项

转载 作者:太空宇宙 更新时间:2023-11-04 14:00:54 25 4
gpt4 key购买 nike

我创建了一个 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

  1. 将事件处理程序附加到您的按钮
  2. 获取单选元素值
  3. 比较

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com