Dynamically get radio button group name using jQuery
Asked Answered
J

2

12

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>
Joist answered 7/4, 2011 at 7:6 Comment(0)
L
23
$('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'

Landers answered 7/4, 2011 at 7:7 Comment(1)
Thanks so much! Discovered that using this.name also does the trick. Thanks!Joist
M
3

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);
});
Menam answered 7/4, 2011 at 7:14 Comment(4)
If someone could format the code for me, that'd be awesome; iPhone seems to be in an awkward mood... =/Menam
Thanks David. Unfortunately the code formatting appeared in preview mode only.Joist
Fixed it, I've no idea why it didn't work before but I just removed all whitespaces and reinserted them.Stercoricolous
Thanks, @Georg, I'm sure the iPhone must use some non-standard whitespace character, for some reason. Sometimes...sigh.Menam

© 2022 - 2024 — McMap. All rights reserved.