我最近发现了一个 StackOverflow 答案,其中给出了关于如何使用 jQuery 获取选中的单选按钮的值 https://stackoverflow.com/questions/596351/how-can-i-get-which-radio-is-selected-via-jquery:
var radioVal = $("#myFormID input:radio[name='radioFieldName']:checked").val();
alert('Selected radio button value = ' + radioVal);
现在我试图找到选中的单选按钮的从零开始的索引。我认为这会相对简单:
var radioIdx = $("#myFormID input:radio[name='radioFieldName']:checked").index();
然而,radioIdx
总是返回一个值-1
。关于我可能做错了什么有什么想法吗?
这应该有效。您可以在一行中完成所有操作,但我将其分解以使其更易于阅读:
var radioButtons = $("#myFormID input:radio[name='radioFieldName']");
var selectedIndex = radioButtons.index(radioButtons.find(':checked'));
EDIT:验证您的选择器是否正确。一步步分解:
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);
哪一步没有产生预期的价值?
EDIT:显示最终解决方案
var radioButtons = $("#myFormID input:radio[name='radioFieldName']");
var selectedIndex = radioButtons.index(radioButtons.filter(':checked'));
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)