Pavel Filimonov
Pavel Filimonov

Reputation: 33

How to handle click events on div

I have a data set of items coming from a SQL database. Those items are displayed in multiple divs like:

 <?php
 $url = 'DataBase';

 $json_response = file_get_contents ( $url );

 $json_arr = json_decode ( $json_response, true );

 for($i = count ( $json_arr )-1; $i > 0;  $i--) {
 $json_obj = $json_arr [$i];


 echo '<div id="MyDIV">';
 echo $json_obj ['id'] ;
 echo $json_obj ['title'];  
 echo $json_obj ['article'];  
 echo '<button id="read_more_btn">Read more</button>';
 echo '</div>'
 }
 ?>

My problem is that I cannot handle click events for EACH div, so I cannot identify which item has been clicked. I’ve been searching for a solution for quite a while, but haven’t found anything. So my question is – how can I identify the clicked item?

EDIT I have no idea how I can dynamically assign an ID to a button

Upvotes: 3

Views: 130

Answers (3)

geedubb
geedubb

Reputation: 4057

You could use a data attributes (HTML5 assumed) to attach the Id as meta data to your divs. Your PHP (note I am adding data-id attributes):

<?php
 $url = 'DataBase';
 $json_response = file_get_contents ( $url );
 $json_arr = json_decode ( $json_response, true );
 for($i = count ( $json_arr )-1; $i > 0;  $i--) {
   $json_obj = $json_arr [$i];
   echo '<div data-id="' . $json_obj['id'] . '">';
   echo $json_obj ['id'] ;
   echo $json_obj ['title'];  
   echo $json_obj ['article'];  
   echo '<button id="read_more_btn">Read more</button>';
   echo '</div>'
 }
 ?>

JS - simple click handler attachment, using jQuery .data() [docs] to get data attribute:

$('div').click(function(e) {
    var id = $(this).data("id");
    alert(id);
});

JSFiddle Demo

Upvotes: 3

Caleb Lewis
Caleb Lewis

Reputation: 543

How about when creating the html in the php, you echo the id inside the class.
echo '<div id="mydiv-' . $json_obj['id'] . '">';

So now in the html, it's going to look like
<div id="mydiv-1"> ... </div>
<div id="mydiv-2"> ... </div>
<div id="mydiv-3"> ... </div>
etc.

And then in Javascript, you could access them the same way you access any tag.

$('#mydiv-1').click(function(e){
    console.log('a div was clicked');
    console.log($(this))
});

So in order to assign listeners to each div, you could do a loop

for(var i = 1;$('#mydiv-container').children().length >= i,i++)
{
     $('#mydiv-' + i).click(function(){ 

}

Make sure to add a container for all the divs.

Upvotes: 2

lolbas
lolbas

Reputation: 794

Give each div a unique numeric class, so your jquery will be

$('div').click(function() {
    var item_id = $(this).attr("class");
    //do stuff here
});

or

$('div').click(function() {
    var item_id = this.className;
    //do stuff here
});

Upvotes: 1

Related Questions