【问题标题】:How to show specific value when click on any radio button in console using JavaScript?使用 JavaScript 在控制台中单击任何单选按钮时如何显示特定值?
【发布时间】:2020-10-27 15:37:58
【问题描述】:

我很难显示所选单选按钮的值。当我单击问题 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>

【问题讨论】:

  • 与您的问题无关:要对单选按钮进行分组,您需要设置 name 属性。要获得选定的,您需要检查属性checked,如question.checked 或使用选择器.question:checkedradio

标签: javascript forms radio


【解决方案1】:

你可以用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>

【讨论】:

  • 最后,如果没有检查问题如何验证?
  • if(question.checked){ console.log(question.value);} else //not checked
【解决方案2】:

而不是检查循环内的checked 属性。您可以使用 :checked 伪类来仅选择选中的收音机。

function answers(event)
{
    var q = document.querySelectorAll('.question:checked');
    [...q].forEach(question =>{

        console.log(question.value);
    });

    event.preventDefault();
}
<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>

还要注意使用name 属性对单选按钮进行分组。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-05
    • 2019-12-14
    • 1970-01-01
    • 1970-01-01
    • 2015-07-26
    • 1970-01-01
    相关资源
    最近更新 更多