获取 jQuery 中选中的单选按钮的值

Get value of checked radio button in jQuery

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

<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;

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

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

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

$('div.checkbox label input')

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

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

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


值得注意的是,如果只有一个答案是 possible-per-question,那么您可能想要使用 单选按钮来代替

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

在那种情况下,在你的 var 里面只放一个 value-per-question.

是有意义的

然后将所有问题都包裹在 <form> 中,然后使用 .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>