jQuery:根据名称和值选择复选框

MrG*_*MrG 13 jquery

我有以下HTML:

<form id="test">
  <input type="radio" value="A" name="C1"/>
  <a href="javascript:selectCheckbox('C1', 'A');"> OPTION-A </a>

  <input type="radio" value="B" name="C1"/>
  <a href="javascript:selectCheckbox('C1', 'B');"> OPTION-B </a>

 <input type="radio" value="C" name="C1"/>
  <a href="javascript:selectCheckbox('C1', 'C');"> OPTION-C </a>

  // several other: C2, C3, ..
</form>
Run Code Online (Sandbox Code Playgroud)

我正在尝试实施selectCheckbox( chkbox, value),它应该:

  1. 搜索所有收音机name = chkbox并设置attr('checked') = false
  2. 搜索有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 i.e. 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'
Run Code Online (Sandbox Code Playgroud)

请让我知道我做错了什么.非常感谢!

小智 23

试试这个:

$('input:radio[name="' + chkboxName + '"][value="' + value + '"]')
    .attr('checked', 'checked');
Run Code Online (Sandbox Code Playgroud)


MrG*_*MrG 7

谢谢你的帮助,我终于明白了:

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);
}); 
Run Code Online (Sandbox Code Playgroud)

}


tva*_*son 5

我会使用相对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
     });
});

<form id="test">
  <input  type="radio" value="A" name="C1"/>
  <a href="#" class="checkbox-selector"> OPTION-A </a>

  <input  type="radio" value="B" name="C1"/>
  <a href="#" class="checkbox-selector"> OPTION-B </a>

  <input  type="radio" value="C" name="C1"/>
  <a href="#" class="checkbox-selector"> OPTION-C </a>

  <!-- several other: C2, C3, ... -->
</form>
Run Code Online (Sandbox Code Playgroud)


Mid*_*hun 5

如果您的jquery版本> 1.6,则可以使用prop()而不是attr()

请参阅此链接 http://api.jquery.com/prop/

从jQuery 1.6开始,.prop()方法提供了一种显式检索属性值的方法,而.attr()则检索属性.

所以你要找的代码看起来更像

$('input:checkbox[name="Validators"][value="' + v + '"]').prop('checked',true);
Run Code Online (Sandbox Code Playgroud)