1

I am following aM1Ne answer (the one with most vote)of this this thread for binding event, as i am generating multiple element dynamically
My js code looks like

$(document).on('click', ".myCheckBox" , function() {
    //.....
});

Here myCheckBox is the class that is assigned to all generated check box. Now i want the index of the clicked checkbox. I have tried

alert($(this).index());

inside. But it always shows 0. Is there any way to get the index of clicked check box which contains the myCheckBox class?

In HTML i Have a single check box

<input type="checkbox" name="" class="myCheckBox" >

and in a button and on its onclick

$("#clickAdd").click(function()
{
    ("#myDiv").append("<input type=\"checkbox\"  class=\"myCheckBox\" >");
 });
Community
  • 1
  • 1
Saif
  • 6,804
  • 8
  • 40
  • 61
  • updated the question with html @Cerbrus – Saif Sep 29 '14 at 10:09
  • So, what "index" value do you want to get, then? – Cerbrus Sep 29 '14 at 10:11
  • if i add more 3 check box using the `add` button and when clicked any of them i want to know which check box was clicked. @Cerbrus – Saif Sep 29 '14 at 10:15
  • The clicked checkbox is just `this`. – Cerbrus Sep 29 '14 at 10:17
  • Actually what i am looking for is like this http://stackoverflow.com/questions/4996002/jquery-get-index-of-element-as-child-relative-to-parent thread explain we can get the li of a list which was clicked and the `index()` method also worked for tr. it it possible that i can get same type of result for multiple check box with same class.? @Cerbrus – Saif Sep 29 '14 at 10:30

2 Answers2

1

I don't know the real explanation, but this code worked like charm

$(document).on('click', ".myCheckBox" , function() {
     var checkIndex = $(this).closest('.myCheckBox').index('.myCheckBox');
     alert(checkIndex);
});    
Saif
  • 6,804
  • 8
  • 40
  • 61
0

I would take a slightly different approach, if you're able to assign the value while you're generating the checkboxes, eg:

$(cb).data('indexVal', index++);

You can assign arbitrary objects/information with the data method. You can then easily retrieve it within your click event handler:

alert($(this).data('indexVal'));

and it's read straight off the element without worrying where it is in the page.

Working with the HTML/script you've added, I would do this:

var indexVal = 1;
$("#clickAdd").click(function() {
    var inp = $('<input>', {type : 'checkbox' });
    inp.addClass('myCheckBox');
    inp.data('indexVal', indexVal++);
    ("#myDiv").append(inp);
});
James Thorpe
  • 31,411
  • 5
  • 72
  • 93