禁用并启用div内的下一个输入字段

时间:2016-08-23 17:29:14

标签: javascript jquery html

如何在选中或取消选中复选框后启用和禁用一个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 Fiddle here

3 个答案:

答案 0 :(得分: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/

答案 1 :(得分:1)

您需要使用next()函数来查找复选框(在您的情况下为div)之后以及此div中的find()输入之后的下一个元素。

&#13;
&#13;
$(document).ready(function()
{
    $('.box').click(function()
    {
        var set =  $(this).is(':checked') ? false : true;
        $(this).next('div.box-2').find('input').attr('disabled', set)
    });
});
&#13;
<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>
&#13;
&#13;
&#13;

答案 2 :(得分:0)

在你的情况下,你应该使用.next()。 .next()将获取下一个元素,您可以对该元素执行任何操作。

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