我最近遇到了一个StackOverflow答案,它在how to get the value of a checked radio button using 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
。关于我可能做错的任何想法?
答案 0 :(得分:30)
这应该有效。你可以在一行中完成所有操作,但我将其分解以便于阅读:
var radioButtons = $("#myFormID input:radio[name='radioFieldName']");
var selectedIndex = radioButtons.index(radioButtons.find(':checked'));
编辑:验证您的选择器是否正确。逐步分解:
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);
哪一步没有产生这些预期值?
编辑:显示最终解决方案
var radioButtons = $("#myFormID input:radio[name='radioFieldName']");
var selectedIndex = radioButtons.index(radioButtons.filter(':checked'));
答案 1 :(得分:5)
尝试使用index的形式,它允许您指定集合中的元素并返回它在集合中的相对位置:
var radioIdx = $(":radio[name='radioFieldName']")
.index($(":radio[name='radioFieldName']:checked"));
或找到第一个项目与另一个集合中的选择器匹配的版本,并在第二个集合中报告它的位置。
var radioIdx = $(":radio[name='radioFieldName']:checked")
.index(":radio[name='radioFieldName']");
答案 2 :(得分:2)
有几种选择:
1)通过单选按钮列表(也就是没有:checked修饰符)枚举并测试它是否被检查;如果是这样,你就拥有该组中元素的id。
2)更好的方法(imo)是简单地将一些数据与每个元素相关联并提取该数据。因此,如果您为元素提供带有值的“数据索引”属性,则可以简单地调用
$('#myFormID input:radio[name='radioFieldName']:checked').data('index')
并且有价值。
答案 3 :(得分:0)
使用此
alert($("input[name=checkname]:checked").map(function () {return this.value;}).get().join(","));
答案 4 :(得分:0)
虽然这很旧,但试试这个(假设你在单选按钮的点击功能中)
$('#myFormID input:radio[name=radioFieldName]').click(function(){
var index = $('#myFormID input:radio[name=radioFieldName]').index(this);
alert(index);
});
答案 5 :(得分:0)
它返回-1,因为你在检查任何radiobutton之前得到了值。我想你错过了你的听众和索引检查。我刚刚得到了相同的错误,但最后找到了答案,我在检查任何内容之前得到了索引,请检查您的代码安排,上面的代码是正确的。