Search code examples
jqueryindexingradio-buttonselectedindex

jQuery get selected index of radio buttons


I am fully aware that this question has seen numerous variants, so please examine it thoroughly before down-voting it as I'm certain that a clear solution will help many others also.

I have a series of radio buttons being dynamically generated as part of a loop through database records. One radio per record in HTML. Each radio button is being assigned an array index value of the record id;

<input type="radio" id="use_msg_id[1]" value="1" />
<input type="radio" id="use_msg_id[2]" value="2" />
<input type="radio" id="use_msg_id[3]" value="3" />
<input type="radio" id="use_msg_id[4]" value="4" />

When a user clicks, let's say, on the radio button with use_msg_id[3], I need jQuery to be able to gather that index value for me. I know there's a way to do it, but have not been searching the right terms to find the proper solution.

Thanks.


Solution

  • You can use regex to extract number

    $(':radio').change(function(){
        var index = $(this).val().match(/\d+/);
    })
    

    DEMO