I'm trying to do a simple voting button but it works only one time per post per reload.
How should it work: Click "+" -> update query (in django) -> reload a div (change "+" to "-") -> allow to click "-" to undo the upvote
It shows the "-" button after I vote for the first time but when I click it, nothing happens. It works only if I hit "F5" and reload the page.
There are no errors in console.
... some django scripts to check which button should be displayed ...
<span class="upvote"><span postId="{{post.id}}" class="vote" href="upvote/{{post.id}}">+</span></span>
<span class="downvote"><span postId="{{post.id}}" class="vote" href="downvote/{{post.id}}">-</span></span>
...
$(document).ready(function(){
$(".vote").click(function(e){
href = $(this).attr("href");
postId = $(this).attr("postId");
$.ajax({
url: href,
success: function() {
$("#post-"+postId+" >header").load(location.href+ " #post-"+postId+">header>*");
},
});
});
The "postId" and "href" attributes are properly filled
It's not obvious what the problem is based on the code you posted, but I'm guessing that the <span>-</span>
is added to the DOM after you have click on <span>+</span>
. If that is the case, then your problem is that you have only bound $('.vote').on('click'...
to the .vote
elements that were in the DOM when that code first executed on page load. You can fix this by using event delegation to bind the event handler to a static parent element and act on any events coming from children that match your selector:
$(document).on('click', ".vote", function(e){
href = $(this).attr("href");
postId = $(this).attr("postId");
$.ajax({
url: href,
success: function() {
$("#post-"+postId+" >header").load(location.href+ " #post-"+postId+">header>*");
},
});
})