从单选按钮组中获取所有选定值的最佳(和正确)方法是什么?

What is the best (and right) way to get all the selected values from groups of radio buttons

本文关键字:最佳 是什么 方法 单选按钮 获取      更新时间:2023-09-26

我正在学习HTML, JavaScript &NodeJs (I'm just getting started) .

我试图创建一个网站,其中用户将回答一些问题(与单选按钮),当用户点击提交按钮,答案将被发送到服务器)。

我正在创建这个javascript函数的问题:

<script type="text/javascript" >
    var questionCounter = 0;
    var questionId = 0;
    function printQueue(question) {     
        questionId++;
        questionCounter++;  
        var radioName="Q"+questionCounter;
        var id = "Q" + questionCounter;                 
        document.write("<p> <b> " + question + " </b> </p>");                                                                                                                       
        document.write ("<input type='"radio'" id=" + id + " name=" + radioName +
                            " onclick='"check(this.value)'" value='"5'">Best<br>");
        document.write ("<input type='"radio'" id=" + id + " name=" + radioName + 
                                " onclick='"check(this.value)'" value='"4'">Very Good<br>");
        document.write ("<input type='"radio'" id=" + id + " name=" + radioName + 
                                " onclick='"check(this.value)'" value='"3'">Good<br>");
        document.write ("<input type='"radio'" id=" + id + " name=" + radioName +
                                " onclick='"check(this.value)'" value='"2'">Not Good<br>");
        document.write ("<input type='"radio'" id=" + id + " name=" + radioName +
                                " onclick='"check(this.value)'" value='"1'">Worst<br>");
    }
</script>

,并以以下方式调用该函数:

<script type="text/javascript" >                
    printQueue("1.  XXX1 ? ");
    printQueue("2.  XXX2  ? ");
    printQueue("3.  XXX3  ? ");
    ...
    ...
    printQueue("N.  XXXN  ? "); 
</script>

是否有一种方法可以遍历问题并获得每个问题所选答案的值?

我看:如何获取所选单选按钮的值

但是看起来很麻烦…

是否有这样的方法:

1. loop over the questions
   1.1 for each Q getSelected().getvalue() 

谢谢

这可能有帮助

HTML

<form id="myForm">
    <div class='Q'> <span>Q1</span>
        <input type="radio" name="Q1" value="1" />1
        <br />
        <input type="radio" name="Q1" value="2" />2
        <br />
        <input type="radio" name="Q1" value="3" />3
        <br />
    </div>
    <div class='Q'> <span>Q2</span>
        <input type="radio" name="Q2" value="1" />1
        <br />
        <input type="radio" name="Q2" value="2" />2
        <br />
        <input type="radio" name="Q2" value="3" />3
        <br />
    </div>
    <input type='button' value='Get Values' id='temp'>
</form>

JS

$('#temp').on('click', function () {
    var Ans = [];
    $('.Q').each(function (index, Obj) {
        Ans.push({
            "Name ": $(this).find('span').text(),
            "Answer": $(this).find('input[type="radio"]:checked').val()
        })
    })
    console.log(Ans)
});
演示