Topic: abstract redundant javascript code

I have a set of divs which are layered on top of each other, each in its own plane.

<div class="outer">
<div class="inner" id="div_0"> </div>
<div class="inner" id="div_1"> </div>
<div class="inner" id="div_2"> </div>
...
<div class="inner" id="div_25"> </div>
</div>

I have a form element which lists one check box for each div:

%form
  - @analytic_results.each_with_index do |ar, index|
    %input{:type => 'checkbox', :name => index, :id => index}
    = ar.name
    %br

I have a jquery script included which allows me to toggle the visibility for each div (plane):

$("#div_0").css("display","none");
$("#div_1").css("display","none");
...
$("#div_25").css("display","none");

    $("input[name=0]").click(function() {
      if( $(this).is(':checked')) {
       $("#div_0").show();
      } else {
       $("#div_0").hide();
      }
    });
    $("input[name=1]").click(function() {
      if( $(this).is(':checked')) {
       $("#div_1").show();
      } else {
       $("#div_1").hide();
      }
    });
...

up to 25...

Is there a way to combine the status check for each checkbox to toggle the visibility in a single function like

"If checkbox with the name of "1" is checked/unchecked toggle the visibility of div with the id of "div_1"?"

Any help would be greatly appreciated.

Thanks
Juergen

Re: abstract redundant javascript code

Hi

so I figured out the first part of hiding all divs using a jquery regex expression. I did convert the code in the meantime to coffeescript as I am working with rails 3.2...

So

$("#div_0").css("display","none");
$("#div_1").css("display","none");
...
$("#div_25").css("display","none");

becomes:

coffeescript:

$("[id^=div_]").css "display", "none"

or in jquery:

$("[id^=div_]").css("display","none");

Which sets display to none for all elements whose id starts with "div_"

Juergen

Re: abstract redundant javascript code

If your div's should be hidden by default set 'display: none' in css file

Toggling div visibility with checkboxes goes like this (coffee):

toggleHandler = (e)->
   checkbox = $(e.target)
   id = checkbox.attr('name').match(/\d+/)[0]
   div = $('#div_'+id)   
   if checkbox.is(':checked')
     div.show()
   else
     div.hide()
  
$-> $('input[type=checkbox]').bind 'click', toggleHandler