2015-12-21 22 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

完美運作。 –

相關問題