H.H. H.H. - 5 months ago 9
jQuery Question

Uncaught Reference Error and JS functionality

I've been looking at this for a while and I can't seem to find a proper solution for it.

Here is part of my code:

<li style="float: right;">Themes
<ul>
<?php
$db=mysql_connect('localhost','root','');
if(!$db) {
die('Could not connect: '.mysql_error());
}
$connection_string=mysql_select_db('somedb',$db);
$selectSQL='SELECT * FROM color_patterns';
$queryset=mysql_query($selectSQL);
$num=mysql_num_rows($queryset);
if(0==$num) {
echo "No record";
exit;
} else {
while($row=mysql_fetch_assoc($queryset)) {?>
<li onclick="liPosition()">
<?php echo($row['name']);?></li><?php
}
}
?>

</ul>
</li>


this is a list item that contains a drop down list. To populate the dropdown list I make a call to my database and for each row in the table I add an li element to the dropdown. I want to retrieve more information from the db based on which li the user clicks so I made a JS function that should get me the index of the li that's clicked on, (The li index corresponds to the id of another table I want to retrieve information from):

<script>

function liPosition() {
var index = $(this).parent().children().index(this);
alert("You clicked item " + index);
});

</script>


When I click on the li I get an error:
Uncaught ReferenceError: liPosition is not defined after some research I found that I can't pass onclick listeners here but I don't know how to find the index of the li in the while loop otherwise. Is there a way to find the index of an li element in a list that's been generated with a while loop? Any help would be greatly appreciated, Thank you.

Answer

Why not remove the inline JavaScript and go full jQuery?

PHP - use a class to identify the clicked item;

while($row=mysql_fetch_assoc($queryset)) {?>
    <li class="list_item">
    <?php echo($row['name']);?></li><?php
}

jQuery - The selector is the list item's class;

<script>

$(document).on('click', '.list_item', function() {
    var index = $(this).id;
    alert("You clicked item " + index);
});

</script>

In addition: please stop using mysql_* functions. These extensions have been removed in PHP 7. Learn about prepared statements for PDO and MySQLi and consider using PDO, it's really pretty easy.