In my DB I have two tables called 'product' and 'material', I am doing a CRUD for the products and in the 'create' view I extract the list of materials registered in the DB in order to select the amount of materials that were used in the production of a product.
Below is a table which contains a list of checkboxes with the materials, and an input of type number which will record the amount of material used:
<table class="table">
@foreach($material as $mat)
<tr>
<td style="width: 50%">
<input type="checkbox" id="boxMat" name="mat[]" value="{{$mat['id']}}">{{$mat['nombre']}}
</td>
<td style="width: 25%">
<input class="input-group-text" id="unidadM" type="number" name="unidadM[]" min="0" >
</td>
<td style="width: 25%">
{{$mat['unidad']}}
</td>
</tr>
@endforeach
</table>
and the following code in JavaScript
for (var i = 0; i < document.getElementsByName("unidadM[]").length; i++) {
document.getElementByName('mat[]')[i].onchange = function() {
document.getElementByName('unidadM[]')[i].disabled = !this.checked;
}
}
What I want is that when loading the 'create' view, the inputs that are next to the checkbox list are disabled, and are enabled only if the corresponding checkbox is selected.
I recommend that when you create the inputs within a loop, you assign an incremental to it,
id
for exampleid="boxMat1"
,id="boxMat2"
, etc., Since the id must be unique, mentioned this, I will explain the code, we obtain the checkbox labels (I already did that). you are clear), likewise we go through them with afor
, then by means ofid
we add a.addEventListener
typechange
, we obtain theid
one of the selected checkbox and we make asplit()
to obtain only the number (although you can add attributesdata-*
to not occupy it), we save in a variableidNum
the position[1]
that would be the number that we require, then we validate if the check ischecked
enabled the input typenumber
->document.getElementById(
num${idNum}).disabled = false;
and if it is not checked we de-enable it. I hope it is what you require, any questions let me know.