Eugenio Segala Eugenio Segala - 4 months ago 10
Javascript Question

Select element inside same div

I have 4 input type and two div with equal name.

<div>
<input class="palmetta" type="checkbox" name="palmetta[]" value="1"> Palmetta
<input class="palmettah" type="text" value="0" name="palmetta[]" ><br>
</div>

<div>
<input class="palmetta" type="checkbox" name="palmetta[]" value="1"> Palmetta
<input class="palmettah" type="text" value="0" name="palmetta[]" ><br>
</div>


There is a way to target only "palmettah" on the first
div
when I check the "palmetta" on the first
div
?

I have create this:

$("div .palmetta").change(function() {

if(this.checked) {
$(".palmettah").prop('disabled', true);
} else {
$(".palmettah").prop('disabled', false);
}

});


This script disable all
palmettah
but I need to disable only the
palmettah
inside the same
div
of the checked input.

Answer

Select input element based on the change event fired element for that use next() method since it's immediately next to the checkbox. Although if condition is not necessary here instead use this.checked as the second argument in prop() method.

$("div .palmetta").change(function() {
    // get the element `this` refers to it's dom object
    $(this)
       // get the element next to it
       .next()
       // update `disabled` property based on 
       // `checked` property of checkbox
       .prop('disabled', this.checked);
});

$("div .palmetta").change(function() {
  $(this).next().prop('disabled', this.checked);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
  <input class="palmetta" type="checkbox" name="palmetta[]" value="1">Palmetta
  <input class="palmettah" type="text" value="0" name="palmetta[]">
  <br>
</div>

<div>
  <input class="palmetta" type="checkbox" name="palmetta[]" value="1">Palmetta
  <input class="palmettah" type="text" value="0" name="palmetta[]">
  <br>
</div>

Comments