Hypister Hypister - 3 months ago 11
HTML Question

Disable and enable next input field that is inside a div

How I can enable and disable the next input inside one div after check or uncheck a checkbox?

I'm trying with jQuery nextAll, but this don't work if a div is involving the elements. My 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>


I'm actually trying with the following jQuery:

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


I know something's wrong, but I can't make it work.
JS Fiddle here

Answer

You need to use next() function to find next element after checkbox (div in your case) and after that find() input inside this 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>