Improve javascript function that enables checkbox

1

In my form I have inputs that can only be edited after a confirmation of the corresponding checkbox, I have it working at the moment:

link

I use the javascritp function:

document.getElementById('check-praia').onchange = function() {
document.getElementById('input-praia').disabled = !this.checked;
};

I still have several fields, and for each new field I have to edit the .js file and add a new function.

How can I make this code smarter, I say, for example:

PEGAR_ID_DO_CHECKBOX.onchange = function(){
PEGAR_ID_DO_INPUT.disable = !this.checked;
};

My idea was to be able to automatically pick up the check and input id and insert it into the tag. Whenever a given checkbox is clicked it changes the value of the input.

Visualize the jsfiddle for better understanding.

    
asked by anonymous 13.11.2014 / 17:22

1 answer

1

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;
}
    
13.11.2014 / 17:33