The solution
As the hierarchy pattern is very clear (there is always a "checkbox-proximity" class label encompassing a checkbox; the ID of this checkbox is related to the ID of the <input />
), we can make a code that takes advantage of these relationships:
var labels = document.getElementsByClassName("checkbox-proximidade");
for(var i = 0; i < labels.length; i++) labels[i].children[0].addEventListener("change", function(e){
document.getElementById("input-" + e.srcElement.id.split("-")[1]).disabled = !this.checked;
});
The Modified jsfiddle is here.
Functioning
In labels
, capture all the elements <label class="checkbox-proximidade">
, that have checkboxes.
For each of them (through instruction for
), We sail to its only child-element (children[0]
) and in it we add a Listener event change.
Each callback of Listener, when executing, search for an element whose ID ends with the same post-hyphen suffix (split("-")[1]
) ends with the same suffix of <input />
, and enable/disable based on the current state of that <input />
(by the way, pointed by e.srcElement
).
Obs.: note that this solution assumes, in addition to the hierarchy patterns already defined, that each ID will contain only one hyphen! If you use more than one, simply change the function of callback for:
function(e){
var arr_aux = e.srcElement.id.split("-"); // Obtém o array de partes do sufixo.
arr_aux.splice(0, 1); // Remove a primeira parte, que corresponde a "check".
// O join(str) une novamente os elementos do array em uma string,
// ligando-os com a string (str) especificada:
document.getElementById("input-" + arr_aux.join("-")).disabled = !this.checked;
}
Exactly Rui Pimentel, thank you very much, by chance I could explain a little the code, so I could understand better and learn?
– Thallyson Dias
Absolutely. I modified the answer! :)
– Rui Pimentel
Thank you very much, I understood the logic, I didn’t know you could do it. D
– Thallyson Dias