【问题标题】:Getting data from radio button从单选按钮获取数据
【发布时间】:2016-02-28 10:12:53
【问题描述】:

如果选择了单选表单中的选项,我正在尝试弄清楚如何检查并写入控制台。 即使选中了正确的选项,我也会不断收到“未选中”。 有任何想法吗? 我更喜欢不包含 JQuery 的解决方案,因为我学习 HTML 和 JavaScript。

谢谢!!

<body>
<form id="office">
    <label id="ques1"> question 1</label><br/>
        <div class="q1 wrong q1a1"><input type="radio" name="question1"    value="q1a1" /> Answer1 <br/></div>
        <div class="q1 wrong q1a2"><input type="radio" name="question1" value="q1a2" /> Answer2 <br/></div>
        <div class="q1 wrong q1a3"><input type="radio" name="question1" value="q1a3" /> Answer3 <br/></div>
        <div class="q1 right q1a4"><input type="radio" name="question1" value="q1a4" /> Answer4 <br/></div>

            <br/><br/>

     <input type="submit" id="submit" name="submitAnswers" value="Submit Your Answers" onclick="checkFunction()" />


</form>


<script type="text/javascript">

window.onload = function() {

 document.getElementById('submit').onclick = function() {
if (document.querySelector('.q1 wrong q1a1').checked == true) {
  console.log('checked');
} else {
  console.log('not checked');
}
};
};
</script>
</body>

【问题讨论】:

  • 您的代码中的一个错误是document.querySelector('.q1 wrong q1a1') 将无法访问,就像document.querySelector('.q1.wrong.q1a1'),但是您到底想要什么?

标签: javascript html forms radio-button


【解决方案1】:

您在传递给querySelector 函数的选择器中有一个小错误。 div 中的每个类名都应该在前面加上 . 选择器应如下所示.q1.wrong.q1a1。然后您可以查找该 div 内部的输入,例如 .q1.wrong.q1a1 input

window.onload = function() {
  document.getElementById('submit').onclick = function() {
    if (document.querySelector('.q1.wrong.q1a1 input').checked == true) {
      console.log('checked');
    } else {
      console.log('not checked');
    }
  }
}

【讨论】:

    【解决方案2】:

    您正在检查&lt;div&gt; 是否被选中,而不是单选按钮。

    改变这一行:

    if (document.querySelector('.q1 wrong q1a1').checked == true) {
    

    类似于:

    if (document.querySelector('input[type=radio][name=question1]').checked == true) {
    

    【讨论】:

    • ...或document.querySelector('input[name="question1"]:checked').value;
    • @Pamblam 好的,好点。如果还有其他.q1a1s,那可能会更好。
    • 非常感谢您的回答!我尝试了第一个选项,并得到“无法读取属性 'checked' of null”。当我尝试 "('input[name="question1"]:checked')" 我得到 "Uncaught ReferenceError: checkFunction is not defined" 还有其他选项吗?谢谢
    • @user3185970 我刚刚意识到一个错误。没有课程.q1a1 - 我把value 误认为class。对不起。如果你想使用它,你将不得不为所有的无线电元素添加一个类。第二个更好,特别是因为无线电元素使用相同的名称。
    • @user3185970 我现在删除了第一个。就用那个吧。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-12
    • 1970-01-01
    相关资源
    最近更新 更多