Reputation: 25
I am trying to implement like button when after clicked it should increment the number of likes but i am trying to implement inside the php code but it is not working and i am not able to figure out what is the problem here?
<html>
<script>
$(".like_button button").on("click", function() {
var $count = $(this).parent().find('.count');
$count.html($count.html() * 1 + 1);
});
</script>
<?php
echo '<div class="like_button">
<button>Like</button>
<span class="count">0</span>
</div>';
?>
</html>
why this code is not working?
Upvotes: 0
Views: 163
Reputation: 26370
It's because you're selecting your button before it exists. Put $(".like_button button")
after the button :
<?php
echo '<div class="like_button">
<button>Like</button>
<span class="count">0</span>
</div>';
?>
<script>
$(".like_button button").on("click", function() {
var $count = $(this).parent().find('.count');
$count.html($count.html() * 1 + 1);
});
</script>
Edit :
Following up with your comments, you haven't included jQuery but you're trying to use it ($
). Then the solution is simple : include jQuery. And open your console.
Working snippet :
$(".like_button button").on("click", function() {
var $count = $(this).parent().find('.count');
$count.html($count.html() * 1 + 1);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="like_button">
<button>Like</button>
<span class="count">0</span>
</div>
<div class="like_button">
<button>Like</button>
<span class="count">0</span>
</div>
Upvotes: 2