jQuery如何通过属性名和属性值查找表单元素?

9

我想要选中一个单选框,但是我只有元素的name属性和value值作为参考。

我需要一种方法来选中正确的单选框,其中name="accounts\['+i+'\]\[account_status\]\[selected\]"且value="current"在"#form1"中。

我有下面的代码,但它只会选中最后一个单选框。

$('#form1 input[name="accounts\\['+i+'\\]\\[account_status\\]\\[selected\\]"]').attr('checked', true);

谢谢

2个回答

21

您似乎忘记了value部分。因此,它尝试检查所有值而不考虑具体数值。由于一组中只能选中一个单选按钮,因此最后只选中了最后一个。

在末尾添加value即可。

input[name='something'][value='something']

http://jsfiddle.net/KsJCP/


1
下面展示了一种更好的方法来查看此选择的工作方式:
<input type="radio" name="some[thing]" value="one">
<input type="radio" name="some[thing]" value="two">
<input type="radio" name="some[thing]" value="three">
<input type="radio" name="some[thing]" value="four">
<input type="radio" name="some[thing]" value="five">
<input type="radio" name="some[thing]" value="six">

alert('1'); // All are unchecked
$("input[value='four'][name='some\\[thing\\]']").attr("checked",true);
alert('2'); // 4th is checked
$("input[value='four'][name='some\\[thing\\]']").attr("checked",false);
alert('3'); // 4th is unchecked

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接