2016-08-23 69 views
0

如何在選中或取消選中複選框後啓用和禁用一個div內的下一個輸入?
我正在嘗試使用jQuery nextAll,但如果div涉及元素,則不起作用。我的HTML:禁用並啓用div內的下一個輸入字段

<input class='box' type='checkbox'/>Option - 
<div class='box-2' style='display: inline-block'> 
    Quantity <input type='number' disabled/> 
</div> 
<input class='box' type='checkbox'/>Option 2 - 
<div class='box-2' style='display: inline-block'> 
    Quantity <input type='number' disabled/> 
</div> 

實際上,我用下面的jQuery的嘗試:

$(document).ready(function() 
{ 
    $('.box').change(function() 
    { 
     var set = $(this).is(':checked') ? false : true; 
     $(this).nextAll('div.box-2 input').first().attr('disabled', set); 
    }); 
}); 

我知道什麼是錯的,但我不能使它發揮作用。 JS Fiddle here

+0

嘗試'.prop('disabled',true);'複選框 –

回答

1

您需要使用next()功能找到下一個元素複選框後,(在你的情況DIV)和後那find()這個div裏面輸入。

$(document).ready(function() 
 
{ 
 
    $('.box').click(function() 
 
    { 
 
     var set = $(this).is(':checked') ? false : true; 
 
     $(this).next('div.box-2').find('input').attr('disabled', set) 
 
    }); 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<input class='box' type='checkbox'/>Option - 
 
<div class='box-2' style='display: inline-block'> 
 
    Quantity <input type='number' disabled/> 
 
</div> 
 
<input class='box' type='checkbox'/>Option 2 - 
 
<div class='box-2' style='display: inline-block'> 
 
    Quantity <input type='number' disabled/> 
 
</div>

+0

現在工作很好。感謝您的解決方案和解釋。 – Hypister

+0

我現在注意到,如果我使用標籤元素,它不起作用:https://jsfiddle.net/Lvf7znxm/5/ 請參閱選項2輸入。 – Hypister

+0

@Hypister是正確的,因爲現在'next()'函數指的是''(但你需要box-2)。這隻會在您刪除此標籤標籤時起作用。 – semanser

1

您必須使用next('.box-2'),之後找到input

HTML:

<input class='box' type='checkbox'/>Option - 
<div class='box-2' style='display: inline-block'> 
    Quantity <input type='number' disabled/> 
</div> 
<input class='box' type='checkbox'/>Option 2 - 
<div class='box-2' style='display: inline-block'> 
    Quantity <input type='number' disabled/> 
</div> 

的jQuery:

工作實例
$(document).ready(function(){ 
    $('.box').change(function(){ 
     var el = $(this).next('.box-2').find('input'); 
     if($(this).is(':checked')){ 
      el.prop('disabled', false); 
     } 
     else{ 
      el.prop('disabled', true); 
     } 
    }); 
}); 

https://jsfiddle.net/Lvf7znxm/4/

+0

謝謝您的回答,但是這也會禁用複選框。 – Hypister

+0

@showdev問題是,當我檢查/取消選中靠近它的複選框時,box-2 div內的輸入字段未被禁用或啓用。 – Hypister

+0

@Hypister我更新了代碼,再試一次。 –

0

在你的情況下,U應該使用的.next()。 .next()將獲取下一個元素,並且您可以對該元素執行任何操作。

$('.box').click(function() 
{ 
    var set = $(this).is(':checked') ? false : true; 
    $(this).next('div.box-2').find('input').attr('disabled', set) 
});