Rishi Rishi - 8 days ago 5
Javascript Question

Executing jquery methods without eval

I have repeating code of

$("#id").addClass('disabled');
and
$("#li-hzd").removeClass('disabled');
in my code for multiple ids in multiple functions. So I am trying to write some generic routine something like,

function toggleClass(id,classname,action){
$("#"+ id") +"." + classname+"("+action+")
}


which can be called something like,

toggleClass(id,'addClass','disabled');
toggleClass(id,'removeClass','disabled');


I believe something can be done using eval() but I also read it's bad practice to use eval. So any idea how to accomplish ?

Answer

You can also get the method by using bracket notation.

function toggleClass(id, action, classname){
    $("#"+ id)[action](classname) 
}

toggleClass(id,'addClass','disabled');
toggleClass(id,'removeClass','disabled');