0

There are three buttons. When I click on any of them - I want to see the number of clicked button in <span>.

<button>1st button</button>
<button>2nd button</button>
<button>3rd button</button>

<span></span>

Firstly, I decided to use for-loop, but I know, that it keeps only last value.

for ( var i = 0; i< 3; i++ ) {
    $('button:eq(' + i + ')').click(function() {
        $('span').append(i + 'button was clicked');
    });
}

jsFiddle

Maybe, $.each() function will help me?

Vlad Holubiev
  • 4,876
  • 7
  • 44
  • 59

4 Answers4

7

You don't need to loop, just bind the handler and use .index() which returns the index of the selected button.

$('button').click(function() {
    $('span').append($(this).index() + 'button was clicked');
});

DEMO: http://jsfiddle.net/RefT2/2/

Selvakumar Arumugam
  • 79,297
  • 15
  • 120
  • 134
6

You don't need a loop for this. You can use .index()

$('button').click(function() {
    $('span').append($(this).index() + 'button was clicked');
});

Declaring multiple event handlers is not a good idea when you can have a single one and you can handle it according to the element it is executed on. The context provides enough information for you to use. If you use a tool to validate your code, like JSLint, you will find out that it advises against declaring functions within a loop.

Konstantin Dinev
  • 34,219
  • 14
  • 75
  • 100
2

While the answers give you alternate/better ways of doing what you are looking for, you need a closure (anonymous self executing function)

for (var i = 0; i < 3; i++) {
    (function (i) {
        $('button:eq(' + i + ')').click(function () {
            $('span').append((i + 1) + 'button was clicked');
        });
    }(i));
}

Check this fiddle: http://jsfiddle.net/RefT2/1/

karthikr
  • 97,368
  • 26
  • 197
  • 188
1

Try this:

 $('button').click(function(){
        $('span').append(($(this).index()+1)  + 'button was clicked'); 
    });

Demo : http://jsfiddle.net/RefT2/3/

Md. Al-Amin
  • 1,423
  • 1
  • 13
  • 26