1👍
✅
You can give data-span="{{ post.id }}"
to your totalRating
span .Then , whenever user click on any button you can get data-id
and use that to refer span tag i.e : $("span[data-span=" + postId + "]")
. Also , you can combine both button events as one because i don’t see any difference between them .
Demo Code :
//use only one ..event handler ..
$('.btn-like-up ,.btn-like-down').on('click', function(e) {
e.preventDefault()
let ratingBox = $(this) //refer to your button
let postType = ratingBox.data('type')
let postId = ratingBox.data('id')
let postAction = ratingBox.data('action')
let totalRating = $("span[data-span=" + postId + "]") //refer to span..tag between button
console.log(postId, postAction)
/*$.ajax({
type: 'POST',
//other codes
success: function(response) {*/
//just for demo..
var response = {
"total_rating": 90
}
totalRating.text(response.total_rating);
/* },
error: function(error) {
console.log(error);
},
})*/
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script>
<button class="btn-like-up" data-id="1" type="button" data-type="file" data-action="rate_up">
<i class="bi bi-chevron-up">Up</i>
</button>
<!--added data-span="{{ post.id }}"-->
<span data-span="1" data-count="total_rating">12</span>
<button class="btn-like-down" data-id="1" type="button" data-type="file" data-action="rate_down"><i class="bi bi-chevron-down">Down</i>
</button>
<br/>
<button class="btn-like-up" data-id="2" type="button" data-type="file" data-action="rate_up">
<i class="bi bi-chevron-up">Up</i>
</button>
<span data-span="2" data-count="total_rating">12</span>
<button class="btn-like-down" data-id="2" type="button" data-type="file" data-action="rate_down"><i class="bi bi-chevron-down">Down</i>
</button>
Source:stackexchange.com