tags:

views:

37

answers:

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

$i is auto generated by loop - which could lead to:

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

etc. where each $i is different.

How do I get value of particular $i (using jQuery), when div is clicked.

In standard JS I would use onClick($i). In jQuery I just do not know, how to pick that val.

+2  A: 

If you don't have any other way to identify the <div> elements, this would place a handler on every <div> on the page.

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

The .text() method will return the text content for that <div>, (as well as any nested elements).

If you only wanted the click event on certain <div> elements, the best is to add a class, and select the correct ones based on that.

$('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 all within the same ancestor element, you could use .delegate() instead, which will place one handler on the ancestor 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)

patrick dw
+1 too quick...
karim79
@karim79 - When I get to a question and I see *"viewed 0 times"*, I know I have a fighting chance. :o)
patrick dw
@ patrick dw:Thank you very much for taking time to explain it to me,now it seems so simple.Before posting I was googlin' quite a bit, but I was not able to ask se the right question.thank you againJeff
Jeffz
+5  A: 
$('div').click(function(event){
  alert($(this).text());
});

A more efficient solution (since it seems you have a lot of <div>s would be to add a live event to the wrapping element of those, like this:

$('#container').live('click', function(event){
   if(event.target.tagName == "DIV") alert($(event.target).text());
});
Pablo Fernandez
For your second code example, to get the text for the correct `<div>` you'll want to do `$(event.target).text()` instead. `this` refers to the `#container` element. ...or do `#container div` in the selector to use `this`.
patrick dw
True! I'll edit it right now
Pablo Fernandez
Pablo,Thank you for the time you took writing your explanation.Jeff
Jeffz
Cool man, no problem. I really did not explain thoroughly how live events work (and the **do** come in handy believe me), you can read about those here -> http://api.jquery.com/live/
Pablo Fernandez