jQuery:如何获取已检查单选按钮的索引

Mas*_*Net 18 jquery radio-button

我最近遇到了一个StackOverflow答案,它给出了如何使用jQuery获取已检查单选按钮的值的优秀指令:

var radioVal = $("#myFormID input:radio[name='radioFieldName']:checked").val();
alert('Selected radio button value = ' + radioVal);
Run Code Online (Sandbox Code Playgroud)

现在我试图找到已检查单选按钮的从零开始的索引.我认为这会相对简单:

var radioIdx = $("#myFormID input:radio[name='radioFieldName']:checked").index();
Run Code Online (Sandbox Code Playgroud)

但是,radioIdx总是返回值-1.关于我可能做错的任何想法?

Kel*_*sey 33

这应该工作.你可以在一行中完成所有操作,但我将其分解以使其更易于阅读:

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

编辑: 验证您的选择器是否正确.逐步分解:

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);
Run Code Online (Sandbox Code Playgroud)

哪一步没有产生这些预期值?

编辑:显示最终解决方案

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

  • @AspNyc尝试`radioButtons.index(radioButtons.filter(':checked'));` (2认同)

tva*_*son 5

尝试使用索引的形式,该索引允许您在集合中指定元素并返回其在集合中的相对位置:

var radioIdx = $(":radio[name='radioFieldName']")
                    .index($(":radio[name='radioFieldName']:checked")); 
Run Code Online (Sandbox Code Playgroud)

或找到与第一个集合中的选择器匹配的第一个项目并报告其在第二个集合中的位置的版本。

var radioIdx = $(":radio[name='radioFieldName']:checked")
                   .index(":radio[name='radioFieldName']");
Run Code Online (Sandbox Code Playgroud)