MicFin
MicFin

Reputation: 2501

JQuery change class and show div when checkbox is checked

When a checkbox is checked, I am trying to change the CSS class of an element and show another element. Currently I have very undry code and repeat the following changing the 0 to 1, 2, 3, etc.

    $("#form-0").hide();
    $('#checkbox-0').click(function () {
      $("#form-0").toggle(this.checked);
      $("#div-0").toggleClass("new_class")
    });

It works fine with my long winded code; however, when I try to iterate through using a for loop, it breaks. There is no error but the element is not shown and the class is not changed.

    for (var i=0; i <= 10; i++) {
      $("#form-"+i).hide();
      $('#checkbox-'+i).click(function () {
        $("#form-"+i).toggle(this.checked);
        $("#div-"+i).toggleClass("new_class")
      });
    };

I am new to JQuery and Javascript, I'm sure I am missing something simple. Any advice?

Upvotes: 0

Views: 394

Answers (1)

ReGdYN
ReGdYN

Reputation: 536

What if you tried this:
Change the html of the elements like this:

<input type="checkbox" id="checkbox-0" class="MYCHECKBOX" />

And then go through them like this:

$for (var i=0; i <= 10; i++) {
    $("#form-"+i).hide();
}
$('.MYCHECKBOX').each(function(index, element) {
  $(element).click(function () {
    $("#form-"+index).toggle(this.checked);
    $("#div-"+index).toggleClass("new_class")
  });
});

Upvotes: 1

Related Questions