mardi 4 août 2015

Optimizing js -Saving values from checkboxes in object

i'm rather new to js and i'd like to optimize my code. I have a group of checkboxes and their boolean values are saved in an object for further calculations.

HTML:

    <fieldset>
        <input type="checkbox" id="checkbox1" onchange="checkbox1Changed()" value="checkbox1">

        <input type="checkbox" id="checkbox2" onchange="checkbox2Changed()" value="checkbox2">

        <input type="checkbox" id="checkbox3" onchange="checkbox3Changed()" value="checkbox3">
    </fieldset>

JS:

//store values for further computation

var boxValues = {
box1: false,
box2: false,
box3: false,
}

//get checkboxvalues from view

var checkbox1 = document.getElementById("checkbox1");
var checkbox2 = document.getElementById("checkbox2");
var checkbox3 = document.getElementById("checkbox3");

//update values in boxValues

function checkbox1Changed() {
    if (checkbox1.checked) {
        boxValues.box1 = true;
    } else {
        boxValues.box1 = false;
    }
}
function checkbox2Changed() {
    if (checkbox2.checked) {
        boxValues.box2 = true;
    } else {
        boxValues.box2 = false;
    }
}
function checkbox3Changed() {
    if (checkbox3.checked) {
        boxValues.box3 = true;
    } else {
        boxValues.box3 = false;
    }
}

Since i plan on having approximately 20 checkboxes in the view there would be a lot of repeating code. Does anyone know a smarter way to do that?

Thanks in advance!

Vin




Aucun commentaire:

Enregistrer un commentaire