Fred J. Fred J. - 6 months ago 45
Javascript Question

get the checked radio button in each radio group

This code tries to get the value of the

value
attribute in the checked radio button in each radio group. but can't get it to work. Thanks



let doc = {};
$('.radio-group').each(function () {
doc.id = $(this).attr('_id');
$(this).children.each(function () {
let validName = $($(this):checked).attr('value');
doc.checkedName = validName;
}
})


<div class='radio-group' _id='abc'>
<label class='radio-item'>
<input class='radio-icon' value='value 1' name='g' type='radio'></input>
<span class='radio-label'>choose me </span>
</label>
<label class='radio-item'>
<input class='radio-icon' value='value 2' name='g' type='radio'></input>
<span class='radio-label'>choose me </span>
</label>
</div>

Answer

Using $(".radio-group input:checked") you can select every checked input that is child of .radio-group.

$(".radio-group input").click(function(){
    var doc = [];
    $(".radio-group input:checked").each(function(index) {
        var id = $(this).closest(".radio-group").attr('_id');
        doc.push(id);
    });
    console.log(doc);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="radio-group" _id="id1">
    <input type="radio" /> 
    <label>Item 1</label>
</div>
<div class="radio-group" _id="id2">
    <input type="radio" /> 
    <label>Item 2</label>
</div>
<div class="radio-group" _id="id3">
    <input type="radio" /> 
    <label>Item 3</label>
</div>
<div class="radio-group" _id="id4">
    <input type="radio" /> 
    <label>Item 4</label>
</div>