1

Why does this work:

var m = 1;
jQuery('#div_sel'+m).click(function() { 
    jQuery('input[id="sel'+m+'"]').val('blahblah'); 
});

but not this:

var m = 1; 
while (m < 8) {
    jQuery('#div_sel'+m).click(function() { 
        jQuery('input[id="sel'+m+'"]').val('blahblah');
    });
    m += 1;
}
gen_Eric
  • 223,194
  • 41
  • 299
  • 337
Frank
  • 323
  • 2
  • 16
  • 2
    common for loop variable scoping mistake. there must be a duplicate – Kevin B Apr 09 '13 at 15:33
  • possible duplicate of [Strange things in JavaScript "for"](http://stackoverflow.com/questions/3150010/strange-things-in-javascript-for) – Kevin B Apr 09 '13 at 15:36

1 Answers1

5

Because the global value of m will be set to 8 when the loop finishes and when event is fired your div selector will be input[id="sel'+8+'"]'

You can use attribute selector with wild card to bind event. You can get the index from the id by removing div_sel from id and use the index for making id of input and use id selector.

jQuery('id^=div_sel]').click(function() { 
     index = this.id.replace('div_sel', '');
     jQuery('#sel'+ index).val('blahblah');
});
Adil
  • 146,340
  • 25
  • 209
  • 204