选中的单选按钮的

选中的单选按钮的

本文介绍了jQuery:如何获取选中的单选按钮的索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近遇到了一个StackOverflow答案,该答案在:

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 = $("#myFormID input:radio[name='radioFieldName']:checked").val();
alert('Selected radio button value = ' + radioVal);

现在,我正在尝试查找选中的单选按钮的从零开始的索引.我认为这会相对简单:

Now I'm trying to find the zero-based index of the checked radio button. I thought it would be relatively simple:

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

但是,radioIdx始终返回值-1.关于我可能做错了什么的任何想法?

However, radioIdx is always returning a value of -1. Any ideas on what I might be doing wrong?

推荐答案

这应该有效.您可以在一行中完成所有操作,但为了方便阅读,我将其分解了:

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'));

编辑:确认您的选择器正确.逐步将其分解:

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?

编辑:显示最终解决方案

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

这篇关于jQuery:如何获取选中的单选按钮的索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-12 23:20