0

i have code for jquery like this

HTML : 
<table class="display">
  <tr>
    <td style="vertical-align:top;">
    <table class="display">
      <thead>
        <tr>
          <td><label><input type="checkbox" class="menu_3"/> menu 3</label></td>
        </tr>
      </thead>
    </table>
    <table class="display table-hover">
      <tbody>
            <tr>
            <td><label><input type="checkbox" class="submenu_3"/> submenu 3</label></td>
        </tr>
                <tr>
            <td><label><input type="checkbox" class="submenu_3"/> submenu 3</label></td>
        </tr>
              </tbody>
    </table>
    </td>
</td>
</tr>
</table>
JQUERY
for(i=1;i<=6;i++){
        $(".menu_"+i).change(function(){
            $(".submenu_"+i).attr("checked", this.checked);
        });
    }

i want to check menu 3, then all submenu 3 checked too, and somehow it not works, because i parameter is missing..

i dont know what is happen..

help me guys..

Jin Sun
  • 91
  • 1
  • 2
  • 12
  • When the `change` event occurs, `i` will always be equal to `6`. You can use an IIFE like Arun to fix this, or you can omit the loop and use jQuery to do that logic for you like Adeneo. – Jasper Jul 03 '13 at 17:40

2 Answers2

1

it should be

for(i=1;i<=6;i++){
    (function(it){
        $(".menu_"+it).change(function(){
            $(".submenu_"+it).prop("checked", this.checked);
        });
    })(i)
}

The problem is the usage of closure variable i, also ready the answer to this question

Community
  • 1
  • 1
Arun P Johny
  • 384,651
  • 66
  • 527
  • 531
1

You can use the starts with selector to select all .menu_* elements, and then slice() to get the number to select the relevant .submenu_* elements etc. No need for a loop :

$('[class^="menu_"]').on('change', function(){
    $(".submenu_" + this.className.slice(-1)).prop("checked", this.checked);
});

FIDDLE

adeneo
  • 312,895
  • 29
  • 395
  • 388
  • It binds a change event handler to all elements that has a class that starts with `menu_`, like `menu_1` or `menu_30000` etc. Then it gets the last number and adds it to `.submenu_` to select the right elements, and this would only work with elements with one single class and one single trailing number, but that's how your example code is written, so as long as your actual code is the same, there shouldn't be an issue. – adeneo Jul 03 '13 at 17:48