Reputation: 4286
My HTML code goes like this:
<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>
I want to iterate the above div tags with id as single and then get the value of selected radio button within each div tag with id as single. The jQuery code written is:
$("input[name=single]").each( function() {
var val = $('input[name=answer]:checked').val();
alert(val);
});
The above jQuery code doesn't seem to work. Pls. advice how can I fix it?
Upvotes: 0
Views: 7726
Reputation: 473
A simpler solution is
$('.single').on('click',function(e) {
alert($($(this).find("input[type=radio]:checked")).attr('id'));
});
Upvotes: 0
Reputation: 20850
Same IDs can't exist on the same html, you should use class in that case.
Here is demo. Try it:
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);
});
Upvotes: 0
Reputation: 68420
HTML
(notice that I changed Id
by class
since repeated ids are not allowed
<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);
});
Upvotes: 5
Reputation: 47657
Try this - http://jsfiddle.net/NfLwy/
$("div.single input:checked").each( function() {
alert( $(this).val() );
});
And the id
should be unique. Replace maybe with a class
Upvotes: 2