0

Working on a poll/voting system where people can click to see results before voting, and then click back again to see the options once more.

The problem is when loading in the results, the button I load to show the options again won't seem to work:

The code for them is basically the same (I've put an alert to test if it was even picking up the button, it is not):

$('.results_button').click(function() {
    var poll_id = $(this).data('poll-id');
    $('.poll_content').load('/includes/ajax/poll_results.php', {'poll_id':poll_id});
});

$('.back_vote_button').click(function() {
    window.alert("Test");
    //var poll_id = $(this).data('poll-id');
    //$('.poll_content').load('/includes/ajax/poll_options.php', {'poll_id':poll_id});
});

The actual code to the back_vote_button is this for example:

<button name="pollresults" class="back_vote_button" data-poll-id="1">Back to voting</button>

Is there something I am missing about interacting with jquery loaded content?

NaughtySquid
  • 1,947
  • 3
  • 29
  • 44

1 Answers1

2

Is your button being created after the doc is loaded? If doesn't exist at the time that the document is created, the listener is not bound. You can either bind a listener event or you can change the click to listen to an already created object, for a bad example try this:

$(document).on('click', '.back_vote_button', function(){ 
     window.alert("Test");
 });

this should work but it will listen every time you click on the body and then determine what you clicked on if this were the problem.

TylerT
  • 69
  • 6
  • That works, but what's the "cleaner" way to do it, as you say it's a bad example? – NaughtySquid Feb 14 '16 at 13:00
  • i would suggest narrowing your search, document.on click will fire every time you click the window, if you narrow it down to where the button will live, say "$('#voteButtonContainer').on('click', '.back_vote_b..." it will only listen when the area with the id of 'voteButtonContainer' is clicked. so just narrowing down where it is listening by only listening in the container or area you know the button will exist. – TylerT Feb 17 '16 at 21:09