3

I tried to bind alert on my buttons:

for(var i=1; i<=3; i++){
   $('#' + i).live('click', function(){
       alert(i);
   });
};

It is my html code:

<input id="1" type="button" value="one">
<input id="2" type="button" value="two">
<input id="3" type="button" value="three">

But I get 4 on all buttons. How to fix it to get correctly alert values? (1, 2, 3 and etc..)

http://jsfiddle.net/sergey1986/UFjsM/

Cœur
  • 37,241
  • 25
  • 195
  • 267
Sergey
  • 33
  • 2

4 Answers4

2
for (var i = 1; i <= 3; i++) {
    $('#' + i).live('click', function(i) {
        return function() {
            alert(i);
        };
    }(i));
}

Note that you are using .live wrong, the point is not to bind to each element individually, but to figure out what each element have in common and use that selector:

$("input[type=button]").live(function() {
    alert(this.id);
});
Esailija
  • 138,174
  • 23
  • 272
  • 326
1

Use this.id, as when loop is finished i will have the last value which break the loop.

Live Demo

for(var i=1; i<=3; i++){
   $('#' + i).live('click', function(){
       alert(this.id);
   });
};

Its better to give some common class to all the button and use that class to bind the event.

<input id="1" type="button" value="one" class="someclass">
<input id="2" type="button" value="two" class="someclass">
<input id="3" type="button" value="three" class="someclass">

$('.someclass').live('click', function(){
   alert(this.id);
});

live is deprecated you better use on

$('.someclass').on('click', function(){
   alert(this.id);
});
Adil
  • 146,340
  • 25
  • 209
  • 204
1

Simple:

for(var i=1; i<=3; i++){
   $('#' + i).live('click', function(){
       alert(this.id);
   });
}

Fiddle: http://jsfiddle.net/rzpXK/

Praveen Kumar Purushothaman
  • 164,888
  • 24
  • 203
  • 252
0

There are a lot of things that are (although not wrong per se) not very good practices.

  1. An element's id should not begin with numbers
  2. .live() is deprecated and should be avoided. .on() should be used instead
  3. .live() or .on() should not be bound like that in a loop. They should be done in one shot, using a single selector where possible.
  4. Use of a common class for all your buttons is a better idea if you want the same event to be bound to multiple elements

Try

$('input[type=button]').on('click', function(){
   alert( this.id );
})
Abhilash
  • 1,610
  • 9
  • 19