0

Given a dynamically built list such as :

<ul id="shortcuts">
  <li><input type="checkbox" value="false"/><button>foo</button><button>-</button></li>
  <li><input type="checkbox" value="false"/><button>foo</button><button>-</button></li>
  <!-- possibly many others lis -->
</ul>

So in order to use only one click event listener, I am trying to attach click event to the list and get the list item index that initially spread the event. Any of my attempts succeed so far.

I can get something out of this :

$("#shorcuts").click ( function(evt) {
   alert( evt.target );
});

But I can't get to the "li" html element nor its "index" within the list. Any idea what I am doing wrong ?

Srinu Chinka
  • 1,471
  • 13
  • 19
Loic
  • 2,173
  • 10
  • 13

3 Answers3

0

You need to attache event to li like below

$(function(){
  $('#shortcuts').on('click','li',function(){
    alert($(this).index());
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<ul id="shortcuts">
  <li><input type="checkbox" value="false"/><button>foo</button><button>-</button></li>
  <li><input type="checkbox" value="false"/><button>foo</button><button>-</button></li>
  <!-- possibly many others lis -->
</ul>

Here click event will delegate to all lis inside shortcuts and you can get the index of clicked li using .index()

Bhushan Kawadkar
  • 28,279
  • 5
  • 35
  • 57
0

You can get index with JQuery - index function.

$('selector').click(function (event) {
    alert($(this).index());
});

DEMO

OR

$("#shorcuts").on("click","li", function(evt) {
    alert($(this).index());
}

Look at here for more options SO - Source

event-binding-on-dynamically-created-elements

bind-click-event-on-dynamically-created-elements

Community
  • 1
  • 1
SK.
  • 4,174
  • 4
  • 30
  • 48
  • Looks like it's working if the list items are previously created. If they are later added, the event listener is not active for these new elements. – Loic Jul 28 '15 at 09:51
  • @Loic You have to attach click event dynamically when you are creating elements. I have added links to the answer. Have a look. – SK. Jul 28 '15 at 10:05
  • Thanks a lot Mike. Still can't get to work but the links are instructive. – Loic Jul 28 '15 at 11:35
0

$(document).ready(function(){
  $(document).on('click','#shortcuts li',function(e){
    e.preventDefault();
    alert($(this).text());
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul id="shortcuts">
  <li><input type="checkbox" value="false"/><button>foo1</button><button>-</button></li>
  <li><input type="checkbox" value="false"/><button>foo2</button><button>-</button></li>
  <!-- possibly many others lis -->
</ul>
sanjeev shetty
  • 438
  • 4
  • 17