使用jQuery获取子单选按钮的值

时间:2012-06-19 16:29:11

标签: jquery

我的HTML代码如下:

   <div id="single"><br><br>
     1) effew<br>
     <input name="answer0" id="answer0" value="1" type="radio"> ewf
     <input name="answer0" id="answer0" value="2" type="radio"> avb
     </div>
     <div id="single"><br><br>
     2) fe<br>
     <input name="answer1" id="answer1" value="1" type="radio"> few
     <input name="answer1" id="answer1" value="2" type="radio"> eww
     <input name="answer1" id="answer1" value="3" type="radio"> tfs
     </div>

我想迭代上面的id为单一的div标签,然后在id为单一的每个div标签中获取所选单选按钮的值。编写的jQuery代码是:

$("input[name=single]").each( function() {
    var val = $('input[name=answer]:checked').val();
    alert(val);
});

上面的jQuery代码似乎不起作用。 PLS。建议我该如何解决?

4 个答案:

答案 0 :(得分:5)

<强> HTML (注意我已将Id更改为class,因为不允许重复ID

 <div class="single"><br><br>
      1) effew<br>
     <input name="answer0" id="answer0" value="1" type="radio"> ewf
     <input name="answer0" id="answer0" value="2" type="radio"> avb
 </div>
 <div class="single"><br><br>
     2) fe<br>
     <input name="answer1" id="answer1" value="1" type="radio"> few
     <input name="answer1" id="answer1" value="2" type="radio"> eww
     <input name="answer1" id="answer1" value="3" type="radio"> tfs
 </div>

<强> JS

$("div.single input[type=radio]:checked").each( function() {
    alert(this.value);
});

jsFiddle demo

答案 1 :(得分:2)

试试这个 - http://jsfiddle.net/NfLwy/

$("div.single input:checked").each( function() {
    alert( $(this).val() );
});

id应该是唯一的。可以用class

替换

答案 2 :(得分:0)

在同一个html中不能存在相同的ID,在这种情况下你应该使用class 这是demo。试试吧:

HTML

<div class="single"><br><br>
     1) effew<br>
     <input name="answer0" id="answer0" value="1" type="radio" checked> ewf
     <input name="answer0" id="answer0" value="2" type="radio"> avb
</div>
<div class="single"><br><br>
     2) fe<br>
     <input name="answer1" id="answer1" value="1" type="radio"> few
     <input name="answer1" id="answer1" value="2" type="radio"> eww
     <input name="answer1" id="answer1" value="3" type="radio" checked> tfs
</div>​

JS:

 $("div.single input[type=radio]:checked").each( function() {
        var val = $(this).val();
        alert(val);
    });​

答案 3 :(得分:0)

更简单的解决方案是

$('.single').on('click',function(e) {
            alert($($(this).find("input[type=radio]:checked")).attr('id'));
        });