javascript - 使用 JavaScript 在控制台中单击任何单选按钮时如何显示特定值?
问题描述
我很难显示所选单选按钮的值。当我单击问题 1 时,结果 1 应该显示在控制台上,但我得到了单选按钮的所有值。有人可以帮我吗?谢谢
html
<form onsubmit="return answers(event)">
<label>Question 1</label>
<input type="radio" class="question" value="1">
<label>Question 2</label>
<input type="radio" class="question" value="2">
<label>Question 3</label>
<input type="radio" class="question" value="3">
<button type="submit">Submit</button>
</form>
JavaScript
<script>
function answers(event)
{
var q = document.querySelectorAll('.question');
[...q].forEach(question =>{
console.log(question.value);
});
event.preventDefault();
}
</script>
解决方案
您可以检查它是否与question.checked
.
function answers(event)
{
var q = document.querySelectorAll('.question');
[...q].forEach(question =>{
if(question.checked){
console.log(question.value);
}
});
event.preventDefault();
}
您可能还想为所有收音机添加名称,因为收音机的想法是一次只能勾选其中一个。name
为您做到这一点:
<form onsubmit="return answers(event)">
<label>Question 1</label>
<input type="radio" class="question" value="1" name="question">
<label>Question 2</label>
<input type="radio" class="question" value="2" name="question">
<label>Question 3</label>
<input type="radio" class="question" value="3" name="question">
<button type="submit">Submit</button>
</form>
推荐阅读
- c++ - 何时使用 __declspec(noalias)?
- python - 创建和使用线程
- linux - 如何将 awk 命令应用于一定数量的文件?
- asp.net-mvc - DbContext 的新实例
- qt - QML 在鼠标按下时动态转移鼠标所有权
- botframework - 无法为 Bot Framework 网络聊天合成语音
- java - 对 JVM 规范中引用大小的困惑
- javascript - 如何使 p5 中的滑块与 webpack 一起使用?
- angular - mat-stepper 组件中的每一步
- excel - 如何通过 VBA 和 AVDoc 在 Excel 中编辑嵌入的 PDF?