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;
}
2
  • 2
    common for loop variable scoping mistake. there must be a duplicate Commented Apr 9, 2013 at 15:33
  • possible duplicate of Strange things in JavaScript "for" Commented Apr 9, 2013 at 15:36

1 Answer 1

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');
});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.