jQuery:根据名称和值选择复选框
我有以下HTML:
我正在尝试实现selectCheckbox( chkbox, value)
,它应该:
- 搜索
name = chkbox
所有无线电并设置attr('checked') = false
- 搜索
name = chkbox AND val() = value
并设置attr('checked') = true
的无线电
我无法弄清楚,正确的选择器是什么,我尝试了以下没有任何运气:
var name = "#" + chkbox + " :checked"; $(name).each(.. // doesn't work $('#'+chkbox).each( .. // if finds only the first occurence // of ie C1, although I would expect 3 $("input[@name='"+chkbox+"']").each( function() { .. // leaves me with the following error: // Warning: Expected attribute name or namespace but found '@name'
请让我知道我做错了什么。 非常感谢!
我使用相对DOM位置来进行导航。 另请注意,您不能使用具有相同ID的不同元素,但在这种情况下,您无需使用名称上的属性选择器来查找正确的输入。 请注意,您已经知道需要根据单击的链接的位置检查哪些输入。 我更喜欢将代码与标记分开,因此我给链接提供了一个类,使它们易于选择并将单击处理程序应用程序移动到代码中。
更新 :请注意,我删除了代码以取消选中其他无线电。 使用无线电,将其中一个设置为已选中应自动取消选中其他任何一个。
$(function() { $('a.checkbox-selector').click( function() { // get the checkbox immediately preceding the link -- this should // be checked. Checking it should automatically uncheck any other // that may be checked. $(this).prev(':checkbox'); .attr('checked',true); return false; // don't process the link }); });
试试这个:
$('input:radio[name="' + chkboxName + '"][value="' + value + '"]') .attr('checked', 'checked');
谢谢你的帮助,我终于明白了:
function selectTestAnswer( chkbox, value ) { $("[name="+chkbox+"]").each( function() { if ( $(this).val() == value ) $(this).attr('checked', true); else if ( $(this).attr('checked') == true) $(this).attr('checked', false); });
}
如果您的jquery版本> 1.6,则可以使用prop()而不是attr()
请参阅此链接http://api.jquery.com/prop/
从jQuery 1.6开始,.prop()方法提供了一种显式检索属性值的方法,而.attr()则检索属性。
所以你要找的代码看起来更像
$('input:checkbox[name="Validators"][value="' + v + '"]').prop('checked',true);
您不能在一个页面上拥有多个具有相同ID的元素。 您的所有输入元素都具有ID“C1”。
尝试$("input[name='C1'] :checked]")
。 ID应该是唯一的,因此jquery可能不希望返回多个元素。