jquerynextuntil

JS checkbox enable/disable groups of inputs NOT working when inputs wrapped in DIVs


I've been looking for a way to enable/disable groups of inputs with a corresponding checkbox. Finally found one answer that works for me here. However, this only works when the inputs are not wrapped in DIVs. When I add the Bootstrap-classes DIVs, the script stops working. Here is the script:

$('input[type="checkbox"]').change(function(){
    $(this).nextUntil(':not(input:text)').prop('disabled', !this.checked)
}).change()

Not well acquainted with JQuery, I've found out that the nextUntil() method will include everything until the next element which is NOT "input:text". So, I tried expanding this as follows:

$(this).nextUntil(':not(input:text, div)').prop('disabled', !this.checked)

or

$(this).nextUntil(':not(input:text), :not(div)').prop('disabled', !this.checked)

or

$(this).nextUntil(':not(input:text)', ':not(input:text)').prop('disabled', !this.checked)

Nothing works. I did read about listing multiple selectors but apparently don't understand how to correctly do it.

Here is the HTML (dynamically generated). I've commented out the DIVs that break the script. This way it does work, but the layout is ugly.

echo "<div class=\"row\">";
//echo "<div class=\"form-group col-md-1\">";
echo "<input class=\"form-control\" type=\"checkbox\" />";
//echo "</div>";
//echo "<div class=\"form-group col-md-3\">";
echo "<input class=\"form-control\" type=\"text\" name=\"phrase_original[]\" value=\"".$original."\" />";
//echo "</div>";
//echo "<div class=\"form-group col-md-5\">";
echo "<input class=\"form-control\" type=\"text\" name=\"phrase_translated[]\" value=\"".$translated."\" />";
//echo "</div>";
echo "</div>";

Please help me write the nextUntil() selectors correctly.


Solution

  • The reason nextUntil won't work is because it selects proceeding siblings, and if you're wrapping your checkbox inside of a <div> it doesn't have any.

    If you want to enable/disable the text inputs based on the state of the checkbox in the same row, you'd be better off using a combination of closest and find:

    $('input[type="checkbox"]').on('change', function() {
        $(this).closest('.row').find('input[type="text"]').prop('disabled', !this.checked);
    });
    

    Here's a fiddle