查找已选中的单选按钮的名称

时间:2012-03-18 17:17:12

标签: javascript jquery radio-button

我的页面有大约25个单选按钮组。当在组中选择单选按钮时,我想执行特定于该组的操作,因此需要 NAME attrib of the radio group。

2 个答案:

答案 0 :(得分:6)

以此HTML为例:

<div id="stackExchange">
  <input type="radio" name="sofu_group" value="Stack Overflow">
  <input type="radio" name="sofu_group" value="Meta Stack Overflow">
  <input type="radio" name="sofu_group" value="Server Fault">
  <input type="radio" name="sofu_group" value="Super User">
</div>
<!-- In no particular order - don't want to start a flame war ;) -->

如果您想要推断出点击的单选按钮所属的组,您可以使用以下内容:

// jQuery ver 1.7+
$("#stackExchange input:radio").on('click',function(){   
  var groupName = $(this).attr('name');
  var groupElements = $(this).parent().find(":radio[name='"+groupName+"']");
});

让我们看看这里发生了什么:

  • $("#stackExchange input:radio") - 此选择器将使用#stackExchange选择器找到所有输入无线电元素,它们是:radio元素的后代。 (Link to docs)。
  • $(this).attr('name') - 这是我们提取所选无线电元素的name属性的地方。 (在我们的示例中 - 这变为sofu_group)。
  • $(this).parent() - 在这种情况下,变量$(this)引用被点击的无线电元素 - 因此我们选择其父级 - #stackExchange元素。
  • parent().find(":radio[name='"+groupName+"']") - 此行将查找元素中保存的所有单选按钮,其名称属性设置为'sofu_group'。

在示例中 - 变量$(this)引用被单击的无线电元素。

答案 1 :(得分:-2)

这可能会给你一些提示

<html>
<head>
<title>My Page</title>
</head>
<body>
<form name="myform" action="http://www.mydomain.com/myformhandler.cgi" method="POST">
<div align="center"><br>
<input type="radio" name="group1" value="Milk"> Milk<br>
<input type="radio" name="group1" value="Butter" checked> Butter<br>
<input type="radio" name="group1" value="Cheese"> Cheese
<hr>
<input type="radio" name="group2" value="Water"> Water<br>
<input type="radio" name="group2" value="Beer"> Beer<br>
<input type="radio" name="group2" value="Wine" checked> Wine<br>
</div>
</form>
</body>
</html>

致电document.getElementsByName("group1").items(0).<propertyname>or<function>