Jquery: get value from click div

<div>'.$i.'</div> 

$ i is automatically generated by the loop - which can lead to:

 <div>'.$i.'</div> <div>'.$i.'</div> <div>'.$i.'</div> 

etc .. where every $ i is different.

How to get the value of a specific $ i (using jQuery) when the div button is pressed.

In standard JS, I will use onClick ($ i). In jQuery, I just don't know how to select this val.

+6
jquery
source share
2 answers

Unless you have another way to identify <div> elements, this places a handler on each <div> on the page.

 $('div').click(function() { var text = $(this).text(); // do something with the text }); 

The .text() method returns the text content for this <div> (as well as any nested elements).

If you only need the click event for specific <div> elements, it is best to add a class and choose the right ones based on this.

 $('div.myClass').click(function() { var text = $(this).text(); // do something with the text }); 

HTML

 <div class="myClass">'.$i.'</div> <div class="myClass">'.$i.'</div> <div class="myClass">'.$i.'</div> <div>some other div</div> 

If the <div> elements are within the same ancestor element, you can instead use .delegate() , in which one ancestor handler will be placed to handle all divs inside.

 $('#parentID').delegate('div.myClass', 'click', function() { var text = $(this).text(); // do something with the text }); 

HTML

 <div id="parentID"> <div class="myClass">'.$i.'</div> <div class="myClass">'.$i.'</div> <div class="myClass">'.$i.'</div> </div> 

(Requires jQuery 1.4 or later)

+17
source share
 $('div').click(function(event){ alert($(this).text()); }); 

A more efficient solution (since it seems like you have a lot of <div> , would be to add a live event to the wrap element of them, for example:

 $('#container').live('click', function(event){ if(event.target.tagName == "DIV") alert($(event.target).text()); }); 
+5
source share

All Articles