Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically get radio button group name using jQuery

I would like to ask if there is a way to get a radio button group name dynamically i.e. optimize the following 2 click functions into one by having [name=some_variable].

I tried:

$('input:radio').click(function() {
    alert($('input:radio:checked').attr('name'));
});

but it always returns me the name of the first radio button group clicked.

$(document).ready(function(){
    $('input:radio[name=q1]').click(function() {
        var ans1 = $('input[name=q1]:radio:checked').val();
        getUserAnswer(1, ans1);
    });

    $('input:radio[name=q2]').click(function() {
        var ans2 = $('input[name=q2]:radio:checked').val();                 
        getUserAnswer(2, ans2);
    });                             
});
<body>
    <ol>
        <li><p>Q1<br />
            <input type="radio" id="q1A" name="q1" value="A" />Q1 A<br />
            <input type="radio" id="q1B" name="q1" value="B" />Q1 B<br />
            <input type="radio" id="q1C" name="q1" value="C" />Q1 C<br />
            <input type="radio" id="q1D" name="q1" value="D" />Q1 D<br />
        </p></li>
        <li><p>Q2<br />
            <input type="radio" id="q2A" name="q2" value="A" />Q2 A<br />
            <input type="radio" id="q2B" name="q2" value="B" />Q2 B<br />
            <input type="radio" id="q2C" name="q2" value="C" />Q2 C<br />
            <input type="radio" id="q2D" name="q2" value="D" />Q2 D<br />           
        </p></li>
    </ol>
</body>
like image 532
gisc Avatar asked Apr 07 '11 07:04

gisc


2 Answers

$('input:radio').click(function() { 
  console.log($(this).attr('name')); 
}); 

You are selecting new set of elements on click, but you need the attr of the current element so, you need to refer to it with 'this'

like image 159
Headshota Avatar answered Oct 12 '22 01:10

Headshota


Something like the following should work:

$('input').click(function() {
    var thisName = $(this).attr('name');
    var qNum = thisName.substring(1);
    var ans2 = $('input[name=' + thisName + ']:radio:checked').val();
    getUserAnswer(thisName, ans2);
});
like image 31
David Thomas Avatar answered Oct 12 '22 01:10

David Thomas