php - jQuery - Selecting specific button nested within div ul li
Get the solution ↓↓↓I admit to being lost. I am trying to select a button that is nested within line items in a ul nested within a div
Here's the php creating the menubar. It is returned via ajax to a div with an id of "menubar". That part works fine. However, none of my click functions do anything.
echo "<ul>";
echo "<li class = 'menu'><button class = 'menbtn' id='scores'>Scores</button></li>";
echo "<li class = 'menu'><button class = 'menbtn' id='rules'>Rules</button></li>";
echo "<li class = 'menu'><button class = 'menbtn' id='courses'>Courses</button></li>";
echo "<li class = 'menu'><button class = 'menbtn' id='history'>Comments</button></li>";
echo "<li class = 'menu'><button class = 'menbtn' id='history'>Reservation</button></li>";
echo "</ul>";
I am assuming I have to use some sort of nested select since a click function for the button with an id of "scores" - $('#scores') does nothing. I have tried various nested selectors and have struck out.
If someone could show me the proper selector for the button with the id of "scores" I'll figure it out from there.
Thank you,
DMD
Answer
Solution:
It seems you are not putting these events in document.ready function. Try putting them in to it.
Example :
$(document).ready(function(){
$("#scores").click(function(){
// Your Stuff
});
});
Answer
Solution:
This will add an event listener to your button.
$(document).on('click', '#scores', function (){
//do something
});
Answer
Solution:
First, you have invalid markup in your html the button Comments and reservations with the same id, second
the selector it's actually simple it just
$("#scores") //<----
But since you don't give too much details about how you're constructing the html it's hard to see what's the real solution only guess. One thing could be that you need to used the eventon
to fired the the event handler after added the html by php
for example
$("#score").on("click", function(){ //do something});
Answer
Solution:
The issue is that jquery can read the new elements returned by the ajax in the dom. To inform jquery to re-read the dom you have to call live.
$('#scores').live("click",function(){
alert("you clicked scores");
});
Answer
Solution:
You can uselive()
method, with the help of this method you can trigger the new element which is added via ajax.
$(document).ready(function(){
$('#scores').live('click',function(){
//Your code
})
});
Share solution ↓
Additional Information:
Link To Answer People are also looking for solutions of the problem: the payload is invalid.
Didn't find the answer?
Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.
Similar questions
Find the answer in similar questions on our website.
Write quick answer
Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.