jQuery: how to get the index of a checked radio button

后端 未结 6 1797
再見小時候
再見小時候 2021-02-12 13:03

I recently came across a StackOverflow answer that gave excellent instructions on how to get the value of a checked radio button using jQuery:

var radioVal = $(\         


        
6条回答
  •  清歌不尽
    2021-02-12 13:44

    This should work. You could do it all in one line but I broke it up to make it easier to read:

    var radioButtons = $("#myFormID input:radio[name='radioFieldName']");
    var selectedIndex = radioButtons.index(radioButtons.find(':checked'));
    

    EDIT: Verify that your selector is correct. Break it down step by step:

    var radioButtons = $("#myFormID input:radio[name='radioFieldName']");
    
    // this should contain the count of all your radio buttons
    var totalFound = radioButtons.length;
    
    // this should contain the checked one
    var checkedRadioButton = radioButtons.find(':checked');
    
    // this should get the index of the found radio button based on the list of all
    var selectedIndex = radioButtons.index(checkedRadioButton);
    

    Which step is not producing the expected value in these?

    EDIT: To show final solution

    var radioButtons = $("#myFormID input:radio[name='radioFieldName']");
    var selectedIndex = radioButtons.index(radioButtons.filter(':checked'));
    

提交回复
热议问题