0

I have a collection of buttons, for which I am selecting using class name:

<button class="validator">One</button>
<button class="validator">Two</button>
<button class="validator">Three</button>
<button class="validator">Four</button>
<button class="validator">Five</button>

I know that I have 5 buttons in jQuery's array, because:

$(".validator").length;
// returns 5

Say for example I click button "Three", how do I get it's index in the array (which in this instance would be 2) ?

4
  • index means it should return 2 in this case right? Commented Aug 5, 2014 at 9:54
  • @RakeshShetty - No, given a Zero based index, it should be 2 Commented Aug 5, 2014 at 9:55
  • use $(this).index(); in the `click event (note zero based) Commented Aug 5, 2014 at 9:55
  • yeah @series0ne sorry see my answer below Commented Aug 5, 2014 at 10:02

3 Answers 3

2

Working Demo : JSFiddle

$('.validator').on('click', function() {
  alert($(this).index());
});

For more info see here

Sign up to request clarification or add additional context in comments.

Comments

0

$('button').on('click', function() { console.log($(this).index()); });

1 Comment

index (without arguments) returns the index of an element among its siblings. We don't actually know if there are only buttons, given the snippet.
0

Try this

jQuery(function(){

    jQuery('.validator').click(function(i){
            console.log(jQuery(this).index());
    });
})

JS Fiddle: http://jsfiddle.net/X74Qw/

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.