Laurent Laurent - 4 months ago 13
HTML Question

Javascript - how avoid this multiples functions for same propose?

I am writing a set of JavaScript functions and was wondering if I could make a function simpler (e.g. a more global function)?

What I have is a set of 5 toggles for which I would like to write a function

toggleOn
and
toggleOff
. What I wrote so far is :

function toggleOn1() {
$('#chk1').bootstrapToggle('on');
}

function toggleOff1() {
$('#chk1').bootstrapToggle('off');
}

function toggleOn2() {
$('#chk2').bootstrapToggle('on');
}

function toggleOff2() {
$('#chk2').bootstrapToggle('off');
}

function toggleOn3() {
$('#chk3').bootstrapToggle('on');
}

function toggleOff3() {
$('#chk3').bootstrapToggle('off');
}

// etc.

Answer

Pass the Jquery selector to the function

function toggle(selector,state){
         $(selector).bootstrapToggle(state); 
}

Both the selector and state will be strings.

You can call it like this

toggle('#chk1','off');
Comments