tags:

views:

22

answers:

2

Hi All,

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

A: 

Yeah, just add a class to each checkbox

<input type="checkbox" class="ex" id="ex1" name="ex" value="Y" <% If IsEx("Y") then%>checked<%end if%> />

and use that instead of id's (and you can also use some selectors like :checked in place of attr('checked') == true)

$(".ex").live("click", function(){
 var cb = $(this);
if(cb.is(':checked')){ 
    cb.parent().removeClass("im-unchecked").addClass("im-checked"); 
}
else{ 
    cb.parent().removeClass("im-checked").addClass("im-unchecked");
}});

EDIT: Fixed typo in above code. And added obligatory jsfiddle: http://jsfiddle.net/X6jxL/

Jamiec
@Jamiec - It worked! Thanks, Much Appreciated
Nasir
+1  A: 

You can use a name attribute selector and cut down on the code using .toggleClass() like this:

$("input[name='ex']:checkbox").live("click", function(){
  $(this).parent().toggleClass("im-unchecked", !this.checked)
                  .toggleClass("im-checked", this.checked); 
});

You can give it a try here.

Nick Craver
@Nick - Thanks a trillion, it worked
Nasir
@Nasir - welcome :)
Nick Craver