1

I want to shorten this code below, but I am not sure how to go about doing so. Any ideas?

$(document).ready(function(){
    $('#mycheckbox').click(function(){
        var item = $(this).attr('#mycheckbox');
        $('.circle').fadeToggle(500);
    });
    $('#mycheckbox2').click(function(){
        var item = $(this).attr('#mycheckbox2');
        $('.circle2').fadeToggle(500);
    });
    $('#mycheckbox3').click(function(){
        var item = $(this).attr('#mycheckbox3');
        $('.circle3').fadeToggle(500);
    });    
    $('#mycheckbox4').click(function(){
        var item = $(this).attr('#mycheckbox4');
        $('.circle4').fadeToggle(500);
    });
});

Edit for HTML:

<div class="circle"><img src="http://www.test.com/img.jpg" /></div>
<div class="circle2"><img src="http://www.test.com/img2.jpg" /></div>
<div class="circle3"><img src="http://www.test.com/img3.jpg" /></div>
<div class="circle4"><img src="http://www.test.com/img4.jpg" /></div>
Afzaal Ahmad Zeeshan
  • 15,669
  • 12
  • 55
  • 103
viksra
  • 97
  • 1
  • 9

3 Answers3

1

What you need is Selector Wildcard

Example:

<div id="jander1"></div>
<div id="jander2"></div>

<script>
    console.log($('[id*=ander]'));//will select all elements that have the string 'ander' included in their id. 
</script>

To relate to your code:

 //select all elements that contain mycheckbox in their id attribute. 
$('[id^=mycheckbox]').click(function(){
        var thisId = $(this).attr("id");//get the actual full id of the clicked element.
        var checkBoxNum = thisId .substr(thisId.length-1); //get the last character (the number)
        //what does the this line do?
        var item = $(this).attr('#mycheckbox'+checkBoxNum ); //use the number to get the attributes. //I don't know why you need this! why creating a seperate attribute with the id? 
      
        $('.circle'+checkBoxNum ).fadeToggle(500);//now we can fade in the desired circle, if mycheckbox3 is clicked, then circle3 will fade toggle. 
    });

Update:

If your list goes large with many numbers (unknown number of characters e.g. 1,001, 325 etc), then you can separate the id name and the number by dash or underscore so you can use split.

str.split('_')[1]; //to get the second part. 

To see in action:

    //e.g. mycheckbox_55
   $('[id^=mycheckbox_]').click(function(){
    var thisId = $(this).attr("id");//get the actual full id of the clicked element.
    var checkBoxNum = thisId.split('_')[1];  //get all characters after _ 
   ..
Community
  • 1
  • 1
Mohammed Joraid
  • 6,202
  • 2
  • 27
  • 38
  • Thank you. This worked perfectly. I just had to modify length-1 to length-2 as circle goes from circle1 to circle23. I had to change the naming convention of circle1 to circle01 to make length-2 work as well. – viksra Mar 22 '14 at 16:48
  • 1
    Glad to help. Since you are changing your naming, then check my update. It's always good to learn new javascript tricks :P – Mohammed Joraid Mar 22 '14 at 17:06
0

Yes, you can select multiple elements in one selecter clause.

Here: https://api.jquery.com/multiple-selector/

From there it is shown that you can seperate multiple elements using , and seperating them using this character like:

$('el1, el2, el3').click(function () {
   /* code here */
}

This way you can select multiple elements and execute code on them!

So your code would be shortened down to:

$('#mycheckbox, #mycheckbox2, #mycheckbox3, #mycheckbox4').click(function () {
   var id = $(this).attr('id'); // get the id
   if(id == 'mycheckbox') {
     $('.circle').fadeToggle(500); // circle without number
   }
   /* add else statements... */
}
Afzaal Ahmad Zeeshan
  • 15,669
  • 12
  • 55
  • 103
0

How about shortening it with a little bit of html changes?

JS :

$(document).ready(function(){
    //.on("click",function(){ ... }) is just a bit better.
    $('[id^=mycheckbox]').on("click",function(){
        var target = $(this).data('target'); 
        $('.'+target).fadeToggle(500);
    });
});

HTML :

<!--Assuming you have these checkboxes, modify them as follows -->
<!--Adding data-target attributes to the checkboxes which contain
    the classes to identify the necessary div-->
<input id="mycheckbox1" type="checkbox" data-target = "circle1">
<input id="mycheckbox2" type="checkbox" data-target = "circle2">
<input id="mycheckbox3" type="checkbox" data-target = "circle3">
<input id="mycheckbox4" type="checkbox" data-target = "circle4">

<!--Adding a general class to the divs-->
<!--Adding a generic class to similar elements also allows 
    you to style all of them together if you want-->
<div class="circle circle1"><img src="http://www.test.com/img.jpg"></div>
<div class="circle circle2"><img src="http://www.test.com/img2.jpg"></div>
<div class="circle circle3"><img src="http://www.test.com/img3.jpg"></div>
<div class="circle circle4"><img src="http://www.test.com/img4.jpg"></div>

NOTE : You will have a little bit more flexibility here and avoid any kind of if-else block inside your js as well.

FIDDLE : http://jsfiddle.net/WRUa8/

Praveen Puglia
  • 5,577
  • 5
  • 34
  • 68