簡體   English   中英

禁用並啟用div內的下一個輸入字段

[英]Disable and enable next input field that is inside a div

選中或取消選中復選框后,如何在一個div內啟用和禁用下一個輸入?
我正在嘗試使用jQuery nextAll ,但是如果div涉及元素,則此方法將無效。 我的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 set =  $(this).is(':checked') ? false : true;
        $(this).nextAll('div.box-2 input').first().attr('disabled', set);
    });
});

我知道出了點問題,但是我無法解決。 JS小提琴在這里

您必須使用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/

您需要使用next()函數在復選框(在您的情況下為div)之后以及此div內部的find()輸入之后查找下一個元素。

 $(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> 

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

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM