jquery click event for a class starting with same initial name
Asked Answered
M

3

6

I have multiple divs added dynamically. The class name is given as "result_"+id where the id is from database table.

<div class="result_137">Gaurab Dahal</div>
<div class="result_138">saurab dahal</div>

enter image description here

How can I write the click event so that it can adddress the div on which it is clicked.

for example I can write the css like below to address all the divs that has classname starting with the string "result".

div[class^="result"]{
    padding:5px;
    width:490px;
    background: rgba(204,204,204,0.5);
    font: 12px arial, verdana, sans-serif;
}
Medallion answered 26/12, 2012 at 7:27 Comment(0)
C
5

For dynamically added div you need to us on() for binding event. You can delegate event to doucment or to parent element of dynamically added elements.

Live Demo

$(document).on('click', 'div[class^=result]', function(){
    alert($(this).text());                              
}); 
Continental answered 26/12, 2012 at 7:28 Comment(2)
i tried that too but that didn't work.. i tried with a simple alert message.Medallion
You need to use on instead of click to bind events with dynamically added elements.Continental
T
3

As you have dynamically added divs so:

$(function(){    // ready handler required
    $(document).on('click', 'div[class^=result]', function(){ // .on in your case
        alert($(this).text());                               // will be helpful
    });
});
Trichina answered 26/12, 2012 at 7:36 Comment(0)
O
0

You can get id of div like this var selection = $(ev.target).attr("id"); where ev is event and then u can apply click function of jquery like this $(selection).live('click',function(){//ur code here });

Odoacer answered 26/12, 2012 at 7:45 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.