检查重复的名称,以及页面加载时单选按钮的值

时间:2012-12-12 10:43:11

标签: jquery html

我有两组相同的单选按钮,一组位于表格顶部和底部(一些UI要求)

问题是当我设置检查单选按钮时,只检查单选按钮的底部

这是我的代码:

//Top Set of Radio Buttons
<input name="optField"  value="Male" type="radio">Male
<input name="optField"  value="Female" type="radio">Female

//Table Here

//Bottom Set of Radio Buttons
<input name="optField"  value="Male" type="radio">Male
<input name="optField"  value="Female" type="radio">Female

Jquery代码:

 $(window).load(function(){

 var $radios = $('input[name=optField]');

 $radios.filter('[value="Male"]').attr('checked',true);

 });

1 个答案:

答案 0 :(得分:1)

您应该为两个选项组指定不同的名称属性。

<强> HTML

<input name="optField"  value="Male" type="radio">Male
<input name="optField"  value="Female" type="radio">Female

//Bottom Set of Radio Buttons
<input name="optField2"  value="Male" type="radio">Male
<input name="optField2"  value="Female" type="radio">Female

<强>的JavaScript

$(window).load(function(){
    var $radios = $('input[name*="optField"]');
    $radios.filter('[value="Male"]').attr('checked',true);
});