Improve javascript function that enables checkbox

Asked

Viewed 164 times

1

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

http://jsfiddle.net/thallysondias/rwn73gnp/

I use the function of javascritp:

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

However I 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, 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. Every time a checkbox is clicked it changes the input value.

View jsfiddle for better understanding.

1 answer

1


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?

  • 1

    Absolutely. I modified the answer! :)

  • Thank you very much, I understood the logic, I didn’t know you could do it. D

Browser other questions tagged

You are not signed in. Login or sign up in order to post.