I have a list of news from a database.
When I start the page all the news titles appear in a list and when I click on them the content of that specific news will show up in a div below.
I'm getting the initial news list like this (this is php code from the index.php file that runs on startup)
$sql = "SELECT title FROM `news`";
$result = mysqli_query($GLOBALS['conn'], $sql);
if (mysqli_num_rows($result) > 0) {
echo "<div id = 'list'>";
echo "<p id = 'text'> All News: </p>";
echo "<ul id ='news_list'>";
while($row = mysqli_fetch_assoc($result)) {
echo "<li><a href='#'>" . $row["title"] . "</a></li>";
}
echo "</ul> </div>";
}
}
And in my script.js I have a function that will show a specific news content when I click on one
$( "#news_list li" ).click(function() {
//do something
});
This works, however I want to sort those news based off a category and view only those specific news instead (instead of all of them).
So my script.js function would look something like
$( ".category" ).click(function() {
var hash = $(this).text(); //name of the news
$("#news_list").empty(); // ul of news list
$.post("get_news_by_category.php",{ajax: true, hash:hash},function(data, status){
var news = "";
for (var i = 0; i < data.length; i++) {
if (data.charAt(i) != "$"){
news = news + data.charAt(i);
}
else{
$( "#news_list" ).append("<li><a href='#'>" + news + "</a></li>");
news = "";
}
}
});
$("#text").text('News by ' + hash);
And my get_news_by_category.php looks something like this
$sql = "SELECT title FROM news WHERE category = '" . $_POST['hash'] . "'";
$result = mysqli_query($GLOBALS['conn'], $sql);
if (mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_assoc($result)) {
echo $row["title"]; echo "$";
}
}
I get the new list with the desired news, but I no longer can click on them. I can only click the news from the initial list, however if I try to click on a news from the list after I filter it, that won't work and I have no idea why.
Hope I've made myself clear.
I would love some input on what I'm doing wrong
EDIT:
I can't thank CBroe and Just a Student enough for the fast response. The solution was using
$('#list').on('click', 'li', function()
instead of my old click function and that actually worked.