【问题标题】:Get value of checked radio button in jQuery获取jQuery中选中的单选按钮的值
【发布时间】:2015-12-26 05:00:42
【问题描述】:

我有一些问题的答案。我想将选中的答案存储在一个变量中。每个答案都是一个单选按钮。例如:

<h4 class='ques1'>Question one here here</h4>
    <div class="checkbox">
        <label>
            <input type="checkbox"> answer 1
        </label>
    </div>
    <div class="checkbox">
        <label>
            <input type="checkbox"> answer 2
        </label>
    </div>

 <h4 class='ques2'>Question two here here</h4>
    <div class="checkbox">
        <label>
            <input type="checkbox"> answer 1
        </label>
    </div>
    <div class="checkbox">
        <label>
            <input type="checkbox"> answer 2
        </label>
    </div>

然后我设置了变量来存储检查的答案……

var ques1Answer, ques2Answer;

我不确定是否需要查询标签标签或输入标签来获取值。但这是我尝试过的:

$('h4.ques1 div.checkbox label input').on('change', function(){
     ques1Answer = $(this).val();
  });

【问题讨论】:

  • 每个答案都是单选按钮是什么意思?您没有使用单选按钮,而是使用复选框......
  • 您的复选框没有值属性。
  • OP应该澄清他的问题

标签: javascript jquery radio-button


【解决方案1】:

你的第一个选择器是错误的'h4.ques1 div.checkbox label input'
DIV 不是 h4.ques1 的孩子,所以使用:

$('div.checkbox label input')

如果你使用.val(),这意味着你实际上有一个值属性,否则你最好分配一些name属性:

<input type="checkbox" name="Question-A-1">
<input type="checkbox" name="Question-A-2">

因此,即使您获得 "on" / "off"(默认值),您也将始终知道这些值所指的 name 实体是什么。


值得注意的是,如果每个问题只有一个答案是可能的,那么您可能希望使用单选按钮

<input type="radio" name="Question-A" value="1">
<input type="radio" name="Question-A" value="2">

在这种情况下,您的vars 中每个问题只保留一个值是有意义的。

比将所有问题都包含在 &lt;form&gt; 中并使用 .serialize() 以获得所有答案:

$("button").click(function(){
 alert( $("form#questionnary").serialize() );
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="questionnary">
  <h4 class='ques1'>Question one here</h4>
  <div class="checkbox">
    <label>
      <input type="radio" name="Question-A" value="1"> answer 1
    </label>
  </div>
  <div class="checkbox">
    <label>
      <input type="radio" name="Question-A" value="2"> answer 2
    </label>
  </div>

  <h4 class='ques2'>Question two here</h4>
  <div class="checkbox">
    <label>
      <input type="radio" name="Question-B" value="1"> answer 1
    </label>
  </div>
  <div class="checkbox">
    <label>
      <input type="radio" name="Question-B" value="2"> answer 2
    </label>
  </div>
</form>


<button>TEST RESULTS</button>

【讨论】:

    猜你喜欢
    • 2016-05-08
    • 2012-01-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-18
    • 1970-01-01
    相关资源
    最近更新 更多