2015-12-21 57 views
1

在面试中提问此问题。我必须检查第一个input [type=text]和下一个input[type=text]之间的所有复选框。两种输入类型的文本都会做同样的事情。选择输入类型旁边的所有checbox

$("input[type=text]").keypress(function() { 
 

 
    console.log("Handler for .keypress() called."); 
 
    $(this).next("input[type=checkbox]").attr('checked',true); 
 
    //$(this).nextUntil("input[type=checkbox]","input[type=text]").attr('checked',true); 
 

 
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0-alpha1/jquery.min.js"></script> 
 

 
<div id="example"> 
 
<input type="text" placeholder="enter something"> 
 
<input type="checkbox" name="something"> 
 
<input type="checkbox" name="something"> 
 
<input type="checkbox" name="something"> 
 
<input type="checkbox" name="something"> 
 
<input type="checkbox" name="something"> 
 

 
<input type="text" placeholder="enter something"> 
 
<input type="checkbox" name="something"> 
 
<input type="checkbox" name="something"> 
 
<input type="checkbox" name="something"> 
 
<input type="checkbox" name="something"> 
 
<input type="checkbox" name="something"> 
 
    
 
</div>

+0

添加类所有的复选框并执行'$( “1类 ”)ATTR(“ 选中”, “选中”)'; –

+0

我必须做到这一点,没有class.is它可能。面试官问我的东西。 –

回答

1

使用nextUntil()

$("input[type=text]").keypress(function() { 

    console.log("Handler for .keypress() called."); 
    $(this).nextUntil("input[type=text]").prop('checked',true); 

}); 

更明确的,如果不是复选框其他元素设置:

$(this).nextUntil("input[type=text]", ":checkbox").prop('checked',true); 
+0

谢谢你,先生。 –

0

应该试试这个。 。

$("input[type=text]").keypress(function() { 
 
    $(this).nextUntil("input[type=text]").attr('checked', true); 
 
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0-alpha1/jquery.min.js"></script> 
 

 
<div id="example"> 
 
    <input type="text" placeholder="enter something"> 
 
    <input type="checkbox" name="something"> 
 
    <input type="checkbox" name="something"> 
 
    <input type="checkbox" name="something"> 
 
    <input type="checkbox" name="something"> 
 
    <input type="checkbox" name="something"> 
 

 
    <input type="text" placeholder="enter something"> 
 
    <input type="checkbox" name="something"> 
 
    <input type="checkbox" name="something"> 
 
    <input type="checkbox" name="something"> 
 
    <input type="checkbox" name="something"> 
 
    <input type="checkbox" name="something"> 
 

 
</div>

+0

完美运作。 –