简体   繁体   English

在 jQuery 中,如何通过 name 属性选择元素?

[英]In jQuery, how do I select an element by its name attribute?

I have 3 radio buttons in my web page, like below:我的网页中有 3 个单选按钮,如下所示:

 <label for="theme-grey"> <input type="radio" id="theme-grey" name="theme" value="grey" />Grey</label> <label for="theme-pink"> <input type="radio" id="theme-pink" name="theme" value="pink" />Pink</label> <label for="theme-green"> <input type="radio" id="theme-green" name="theme" value="green" />Green</label>

In jQuery, I want to get the value of the selected radio button when any of these three are clicked.在 jQuery 中,我想在单击这三个中的任何一个时获取所选单选按钮的值。 In jQuery we have id (#) and class (.) selectors, but what if I want to find a radio button by its name, as below?在 jQuery 中,我们有 id (#) 和 class (.) 选择器,但是如果我想按名称查找单选按钮怎么办,如下所示?

$("<radiobutton name attribute>").click(function(){});

Please tell me how to solve this problem.请告诉我如何解决这个问题。

This should do it, all of this is in thedocumentation , which has a very similar example to this:应该这样做,所有这些都在文档中,其中有一个与此非常相似的示例:

$("input[type='radio'][name='theme']").click(function() {
    var value = $(this).val();
});

I should also note you have multiple identical IDs in that snippet.我还应该注意,您在该片段中有多个相同的 ID。 This is invalid HTML.这是无效的 HTML。 Use classes to group set of elements, not IDs, as they should be unique.使用类来分组元素集,而不是 ID,因为它们应该是唯一的。

To determine which radio button is checked, try this:要确定选中哪个单选按钮,请尝试以下操作:

$('input:radio[name=theme]').click(function() {
  var val = $('input:radio[name=theme]:checked').val();
});

The event will be caught for all of the radio buttons in the group and the value of the selected button will be placed in val.将为组中的所有单选按钮捕获该事件,并且所选按钮的值将放置在 val 中。

Update: After posting I decided that Paolo's answer above is better, since it uses one less DOM traversal.更新:发布后,我认为 Paolo 上面的答案更好,因为它使用了更少的 DOM 遍历。 I am letting this answer stand since it shows how to get the selected element in a way that is cross-browser compatible.我让这个答案站得住脚,因为它展示了如何以跨浏览器兼容的方式获取所选元素。

$('input:radio[name=theme]:checked').val();

另一种方式

$('input:radio[name=theme]').filter(":checked").val()

This works great for me.这对我很有用。 For example you have two radio buttons with the same "name", and you just wanted to get the value of the checked one.例如,您有两个具有相同“名称”的单选按钮,而您只想获取选中的单选按钮的值。 You may try this one.你可以试试这个。

$valueOfTheCheckedRadio = $('[name=radioName]:checked').val();

The following code is used to get the selected radio button value by name以下代码用于按名称获取选中的单选按钮值

jQuery("input:radio[name=theme]:checked").val();

Thanks Adnan谢谢阿德南

For anyone who doesn't want to include a library to do something really simple:对于那些不想包含一个库来做一些非常简单的事情的人:

document.querySelector('[name="theme"]:checked').value;

jsfiddle jsfiddle

For a performance overview of the current answers check here有关当前答案的性能概述,请在此处查看

I found this question as I was researching an error after I upgraded from 1.7.2 of jQuery to 1.8.2.从 jQuery 的 1.7.2 升级到 1.8.2 后,我在研究错误时发现了这个问题。 I'm adding my answer because there has been a change in jQuery 1.8 and higher that changes how this question is answered now.我正在添加我的答案,因为 jQuery 1.8 及更高版本发生了变化,这改变了现在回答这个问题的方式。

With jQuery 1.8 they have deprecated the pseudo-selectors like :radio, :checkbox, :text.在 jQuery 1.8 中,他们弃用了伪选择器,如 :radio、:checkbox、:text。

To do the above now just replace the :radio with [type=radio] .要执行上述操作,只需将:radio替换为[type=radio]即可。

So your answer now becomes for all versions of jQuery 1.8 and above:因此,您的答案现在适用于所有 jQuery 1.8 及更高版本:

$("input[type=radio][name=theme]").click(function() { 
    var value = $(this).val(); 
}); 

You can read about the change on the 1.8 readme and the ticket specific for this change as well as a understand why on the :radio selector page under the Additional Information section.您可以阅读1.8 自述文件中的更改特定于此更改的票证,并在附加信息部分下的:radio 选择器页面上了解原因。

If you'd like to know the value of the default selected radio button before a click event, try this:如果您想知道单击事件之前默认选中单选按钮的值,请尝试以下操作:

alert($("input:radio:checked").val());

You can use filter function if you have more than one radio group on the page, as below如果页面上有多个单选组,您可以使用过滤功能,如下所示

$('input[type=radio]').change(function(){
    var value = $(this).filter(':checked' ).val();
    alert(value);
});

Here is fiddle url这是小提琴网址

http://jsfiddle.net/h6ye7/67/ http://jsfiddle.net/h6ye7/67/

<input type="radio" name="ans3" value="help"> 
<input type="radio" name="ans3" value="help1">
<input type="radio" name="ans3" value="help2">

<input type="radio" name="ans2" value="test"> 
<input type="radio" name="ans2" value="test1">
<input type="radio" name="ans2" value="test2">

<script type="text/javascript">
  var ans3 = jq("input[name='ans3']:checked").val()
  var ans2 = jq("input[name='ans2']:checked").val()
</script>

如果你想要一个真/假值,使用这个:

  $("input:radio[name=theme]").is(":checked")

I you have more than one group of radio buttons on the same page you can also try this to get the value of radio button:如果您在同一页面上有不止一组单选按钮,您也可以尝试这样做来获取单选按钮的值:

$("input:radio[type=radio]").click(function() {
    var value = $(this).val();
    alert(value);
});

Cheers!干杯!

Something like this maybe?可能是这样的?

$("input:radio[name=theme]").click(function() { 
 ...
}); 

When you click on any radio button, I believe it will end up selected, so this is going to be called for the selected radio button.当您单击任何单选按钮时,我相信它最终会被选中,因此将为选定的单选按钮调用它。

也可以使用 CSS 类来定义单选按钮的范围,然后使用以下内容来确定值

$('.radio_check:checked').val()

This worked for me..这对我有用..

HTML: HTML:

<input type="radio" class="radioClass" name="radioName" value="1" />Test<br/>
<input type="radio" class="radioClass" name="radioName" value="2" />Practice<br/>
<input type="radio" class="radioClass" name="radioName" value="3" />Both<br/>

Jquery:查询:

$(".radioClass").each(function() {
        if($(this).is(':checked'))
        alert($(this).val());
    });

Hope it helps..希望能帮助到你..

You might notice using class selector to get value of ASP.NET RadioButton controls is always empty and here is the reason.您可能会注意到使用类选择器获取ASP.NET RadioButton控件的值始终为空,这就是原因。

You create RadioButton control in ASP.NET as below:您在ASP.NET中创建RadioButton控件,如下所示:

<asp:RadioButton runat="server" ID="rbSingle" GroupName="Type" CssClass="radios" Text="Single" />
<asp:RadioButton runat="server" ID="rbDouble" GroupName="Type" CssClass="radios" Text="Double" />
<asp:RadioButton runat="server" ID="rbTriple" GroupName="Type" CssClass="radios" Text="Triple" />

And ASP.NET renders following HTML for your RadioButton并且ASP.NET为您的RadioButton呈现以下 HTML

<span class="radios"><input id="Content_rbSingle" type="radio" name="ctl00$Content$Type" value="rbSingle" /><label for="Content_rbSingle">Single</label></span>
<span class="radios"><input id="Content_rbDouble" type="radio" name="ctl00$Content$Type" value="rbDouble" /><label for="Content_rbDouble">Double</label></span>
<span class="radios"><input id="Content_rbTriple" type="radio" name="ctl00$Content$Type" value="rbTriple" /><label for="Content_rbTriple">Triple</label></span>

For ASP.NET we don't want to use RadioButton control name or id because they can change for any reason out of user's hand (change in container name, form name, usercontrol name, ...) as you can see in code above.对于ASP.NET ,我们不想使用RadioButton控件名称或 id,因为它们可以出于任何原因在用户无法控制的情况下进行更改(容器名称、表单名称、用户控件名称等的更改),如您在上面的代码中所见.

The only remaining feasible way to get the value of the RadioButton using jQuery is using css class as mentioned in this answer to a totally unrelated question as following使用 jQuery 获取RadioButton值的唯一剩余可行方法是使用 css 类,如回答中提到的一个完全不相关的问题,如下所示

$('span.radios input:radio').click(function() {
    var value = $(this).val();
});
$('input:radio[name=theme]').bind(
  'click',
  function(){
    $(this).val();
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM