0

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.

0

1 Answer 1

0

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

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you! All good now. Only a small problem: not sure why, when I first load the page, all inputs are enabled. To disable them, I need to check the box, then uncheck. I see in your fiddle example that the issue doesn't occur. I solved the problem by adding disabled="disabled" to the tag.
In the example fiddle I'm triggering the change (.trigger('change')) event on the checkboxes to set their states

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.