首页 > 解决方案 > 使用 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>

标签: javascriptformsradio

解决方案


您可以检查它是否与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>

推荐阅读