The solution
Since the hierarchy pattern is very clear (there is always a class label "checkbox-proximity" enclosing a checkbox; the ID of that 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 .
Operation
In labels
, we capture all elements <label class="checkbox-proximidade">
, which have the checkboxes.
For each one of them (through the for
statement), we navigate to its single child element ( children[0]
) and add a listener change in>.
Each listener callback, when running, searches 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 this <input />
(by the way, pointed to e.srcElement
).
Obs : Note that this solution assumes, in addition to the hierarchy patterns already defined, that each ID will only contain one hyphen! If you use more than one, simply change the callback function to:
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;
}