Using JQuery, is there a more efficient way of writing this code? See below
The JQuery:
$("#ex1").live("click", function(){
if($("#ex1").attr("checked")==true){
$(this).parent().removeClass("im-unchecked").addClass("im-checked");
}
else if($("#ex1").attr("checked")==false){
$(this).parent().removeClass("im-checked").addClass("im-unchecked");
}});
$("#ex2").live("click", function(){
if($("#ex2").attr("checked")==true){
$(this).parent().removeClass("im-unchecked").addClass("im-checked");
}
else if($("#ex2").attr("checked")==false){
$(this).parent().removeClass("im-checked").addClass("im-unchecked");
}});
The HTML I’m working with:
<label for="ex1" id="ex-label-1">Y <input type="checkbox" id="ex1" name="ex" value="Y" <% If IsEx("Y") then%>checked<%end if%> /></label>
<label for="ex2" id="ex-label-2">M <input type="checkbox" id="ex2" name="ex" value="M" <% If IsEx("M") then%>checked<%end if%> /></label>
<label for="ex5" id="ex-label-3">X <input type="checkbox" id="ex5" name="ex" value="X" <% If IsEx("X") then %>checked<%end if%> /></label>
<label for="ex3" id="ex-label-4">N <input type="checkbox" id="ex3" name="ex" value="N" <% If IsEx("N") then %>checked<%end if%> /></label>
<label for="ex6" id="ex-label-5">L <input type="checkbox" id="ex6" name="ex" value="L" <% If IsEx("L") then %>checked<%end if%> /></label>
<label for="ex7" id="ex-label-6">Z <input type="checkbox" id="ex7" name="ex" value="Z" <% If IsEx("Z") then %>checked<%end if%> /></label>
<label for="ex4" id="ex-label-7">A <input type="checkbox" id="ex4" name="ex" value="A" <% If IsEx("A") then %>checked<%end if%> /></label>
Sorry guys I’m a novice as JavaScript/JQuery
Any help would be greatly appreciated, Thanks
You can use a
nameattribute selector and cut down on the code using.toggleClass()like this:You can give it a try here.