0

I am taking list of data from my database using a loop. I loop one div but the values change depending on what I have in the database. I will want to get the id of the link that i click on from the individual divs. below is my html codes...

<?php
$query = $student->conn->prepare('SELECT * FROM groups');
$query->execute();
$result = $query -> fetchAll();
$count = 0;
foreach ($result as $row) {
    $count = $count + 1;
    $groupName = $row['GpName'];
    $groupAdmin = $row['GpAdmin'];
    $groupPurpose = $row['GpPurpose'];
    $output = "42";
    echo "<div class='animated flipInY col-sm-4'>
                <div class='tile-stats'>
                    <div class='icon'><i class='fa fa-tags'></i></div>
                    <div class='count'>$count</div>
                    <h3 id='groupName'>$groupName</h3>
                    <a id='$groupName' class='display' href='#'><p>Click here display group information.</p></a>
                </div>
            </div>";
}
?>

This is the jQuery code I use. it works in the console but it doesn't work on the page:

$('.display').on('click', function () {
    $(this).next();       
    var id = $(this).prev().val(); 
    alert(id);
});
Don't Panic
  • 41,125
  • 10
  • 61
  • 80
  • 1
    Have a look at [this](http://stackoverflow.com/a/3239600/1272394). – Drewness Feb 22 '16 at 17:39
  • 1
    Right now you're creating duplicate id's (`id='groupName'`) and that will not work. ID's must be unique. There is no `next()` (sibling) after `.display`. You can get rid of that line of code. Typically `var id = $(this).prev('h3').attr('id');` [Quit using `alert()` for troubleshooting.](http://stravid.com/en/stop-the-javascript-alert-madness/), use `console.log()` instead. – Jay Blanchard Feb 22 '16 at 17:39
  • Post the rendered HTML, not the PHP. – j08691 Feb 22 '16 at 17:40
  • 1
    *"It works in the console but it doesn't work on the page"* Is the content loaded with Ajax? – epascarello Feb 22 '16 at 17:44
  • "It works in the console but it doesn't work on the page" - exactly where is your jquery code defined? If it's in a separate .js file loaded in the `head` (or anywhere before the actual html it refers to) then this will be the case. – freedomn-m Feb 22 '16 at 17:58
  • the jquery codes is in the same file. up the page in a php tag – Sire_Clifford Feb 24 '16 at 03:00
  • i have not used ajax to load the content. just php and jquery – Sire_Clifford Feb 24 '16 at 03:00

1 Answers1

0

The statement

It works in the console but it doesn't work on the page

makes me think you are using Ajax so that means you are binding an event to elements that do not exist. So use event bubbling or bind the events after you replace the content.

$(document).on('click', '.display', function () {
    var id = $(this).prev().val(); 
    alert(id);
});
epascarello
  • 204,599
  • 20
  • 195
  • 236