jQuery 获取单选按钮组的值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3464075/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 15:30:22  来源:igfitidea点击:

Get Value of Radio button group

jqueryradio-button

提问by Parampal Pooni

I'm trying to get the value of two radio button groups using the jQuery syntax as given below. When the code below is run I get the value selected from the first radio button group twice instead of getting the value of each individual group.

我正在尝试使用下面给出的 jQuery 语法获取两个单选按钮组的值。当下面的代码运行时,我从第一个单选按钮组中选择了两次,而不是获取每个单独组的值。

Am I doing something obviously wrong here? Thanks for any help :)

我在这里做错了什么吗?谢谢你的帮助 :)

<a href='#' id='check_var'>Check values</a><br/><br/>
<script>
  $('a#check_var').click(function() {
    alert($("input:radio['name=r']:checked").val()+ ' ' +
          $("input:radio['name=s']:checked").val());
  });
</script>
Group 1<br/>
<input type="radio"  name="r" value="radio1"/> radio1
<input type="radio"  name="r" value="radio2"/> radio2
<br/><br/>
Group 2<br/>
<input type="radio"  name="s" value="radio3"/> radio3
<input type="radio"  name="s" value="radio4"/> radio4

回答by Nick Craver

Your quotes only need to surround the value part of the attribute-equals selector, [attr='val'], like this:

你的报价只需要围绕价值的部分属性等于选择[attr='val']像这样:

$('a#check_var').click(function() {
  alert($("input:radio[name='r']:checked").val()+ ' '+
        $("input:radio[name='s']:checked").val());
});?

You can see the working version here.

您可以在此处查看工作版本