如何使用jQuery获取或设置单选按钮列表的选定索引? [英] How to get or set Selected index of the Radio Button List using jquery?

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

问题描述

如何使用索引检查单选按钮. 下面是我的asp.net C#代码的单选按钮列表...

How I can radio button checked using index.. Below is my asp.net C# code for radion button list...

<asp:RadioButtonList runat="server" ID="rdlCategory" CssClass="clsradio" AppendDataBoundItems="true" RepeatDirection="Horizontal" RepeatLayout="Flow" >
</asp:RadioButtonList>

并使用C#动态绑定. 和HTML看起来像

and Bind it using C# dynamically.. and Html looks like

<span class="clsradio" id="ctl00_cphTop_rdlCategory"><input type="radio" value="8" name="ctl00$cphTop$rdlCategory" id="ctl00_cphTop_rdlCategory_0"> 
    <label for="ctl00_cphTop_rdlCategory_0">category1</label>
    <input type="radio" value="11" name="ctl00$cphTop$rdlCategory" id="ctl00_cphTop_rdlCategory_1">
    <label for="ctl00_cphTop_rdlCategory_1">category2</label>
    <input type="radio" value="22" name="ctl00$cphTop$rdlCategory" id="ctl00_cphTop_rdlCategory_2">
    <label for="ctl00_cphTop_rdlCategory_2">category3</label>
    <input type="radio" value="33" name="ctl00$cphTop$rdlCategory" id="ctl00_cphTop_rdlCategory_3">
    <label for="ctl00_cphTop_rdlCategory_3">category4</label>
    <input type="radio" value="34" name="ctl00$cphTop$rdlCategory" id="ctl00_cphTop_rdlCategory_4">
    <label for="ctl00_cphTop_rdlCategory_4">category5</label>
    </span>

我想通过索引值将属性checked = true添加到单选按钮.
假设我通过了index = 2,那么应该选择Category2 ..
或也想在jquery中使用以选择(checked = true)单选按钮索引.

I want to add attribute checked=true to radio button by index value .
suppose, I passed index=2 then it should be selected Category2 ..
or also want to get selected (checked=true) radio button index using in jquery..

我该怎么做?

推荐答案

与选择框不同,单选按钮中实际上没有索引的概念.

Unlike select boxes, there isn't really a concept of an index in radio buttons.

但是您可以在jQuery中执行以下操作:

However you can do something like this in jQuery:

$(".clsradio input:checked").index();

这将使您的跨度内的所有输入框都被选中(如果使用的收音机只有.clsradio组,则您的使用收音机的输入框应仅为一个).

Which will get all the input boxes within your span that are checked (which as your using radio's should only be one, if only one group is inside .clsradio).

这是jsfiddle上的示例

Here is an example on jsfiddle

一个更完整的证明示例(但较慢)将是:

A more full proof example (but slower) would be:

$("input[name$='rdlCategory']:checked").index();

哪个输入以rdlCategory结尾.您甚至可以添加:radio",但不需要.

Which gets inputs ending in rdlCategory. You could even add ":radio" but you don't need to.

编辑2-通过传入索引进行检查.

EDIT 2 - Checking by passing in index.

您可以使用:

 $(".clsradio input:nth-child(5)").attr("checked", "checked");

使用输入"选择器的第n个子级可用作索引.

nth-child using the "input" selector can be used as the index.

这篇关于如何使用jQuery获取或设置单选按钮列表的选定索引?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆