2

In general: What I want is to have PHP output an unordered list with books. When the user clicks on one of the titles, the details will be pulled from the DB and inserted into the page using AJAX.

I can't seem to figure out how to pull the title value from the < li > using javascript, so I can pass that to AJAX.

(To simplify the example code, I left out the AJAX part and am using an alert instead.)

<html>
<head>
<script type="text/javascript">

window.onload = function()
{

      var shelve = document.getElementById( 'books' );
      var books = shelve.getElementsByTagName( 'li' );
      for( var i=0; i < books.length; i++ ){
         books[i].onclick = function(){
        alert(books[i].title); //I know this doesn't work
         };
      }
}

</script>
</head>
<body>

<div id="txtHint"><b>Book info will be listed here using AJAX.</b></div>

<?php show_allBooks(); ?>

</body>
</html>

<?php

function show_allBooks(){

    db_connect();
    $query = "Select * from tblBooks order by title";
    $result = mysql_query($query);
    echo "<ul id='books'>";
    while ($row = mysql_fetch_array($result))
    {
        echo "<li title='" . $row['id'] . "'>" . $row['title'] . "</li>";
    }
    echo "</ul>";
    db_close();
}
?>

I tried fooling around with variations of the following code, but this did not seem to work either.

books[i].getAttribute("title")

Can anyone point me in the right direction? Any help would be greatly appreciated.

2 Answers2

3

By the time your onclick handler gets called, i has been incremented to books.length. Instead, you can reference this to get the element.

var shelve = document.getElementById('books');
var books = shelve.getElementsByTagName('li');
for(var i = 0; i < books.length; i++) {
    books[i].onclick = function () {
        alert(this.title); 
    };
}

http://jsfiddle.net/gilly3/cPMAU/

However, if you do need to know the value of i in the click handler, you can do it by creating your handler in a factory, that is a function that returns a function:

function createBookHandler(books, i) {
    return function() {
        alert(books[i].title);
    };
}
var shelve = document.getElementById('books');
var books = shelve.getElementsByTagName('li');
for(var i = 0; i < books.length; i++) {
    books[i].onclick = createBookHandler(books, i);
}

http://jsfiddle.net/gilly3/cPMAU/1/

gilly3
  • 87,962
  • 25
  • 144
  • 176
0

Start with

books.item(i)

Then it depends how title is stored in the list. If its

<li title="">

then books.item(i).getAttribute("title")

But the closure related answer is probably more important.

Julian
  • 1,522
  • 11
  • 26