How to disable each button after its been clicked, also how to increment like counter through jQuery?
I am building a 'like' button for each comment and posting data using jQuery to PostsController. I am passing the Id value, @item.Id, for each item in the loop and handling the Id through below jQuery code.
@foreach (var item in Model.PostComments)
{
<a id="@item.Id" href="#" class="btn-sm btn-success btn-like"><span class="glyphicon glyphicon-thumbs-up"></span></a>
<span id="commentcounter">@Model.CommentMetrics.Where(a => a.PostCommentId == item.Id).Sum(a => a.VoteValue)</span>
}
and the jQuery code is :
<script>
$(document).ready(function() {
$('a.btn-like').click(function(e) {
e.preventDefault();
$(this).attr("disabled", "disabled");
$('#commentcounter').text(function(i, oldVal) {
return parseInt(oldVal, 10) - 1;
})
$.ajax({
url: '@Url.Action("CommentUp", "Posts")',
data: {
id: this.id
}
});
});
});
</script>
Jquery Documentation
Attributes vs. Properties:
official documentation: http://api.jquery.com/prop/
For your example you need this:
use
$(this).prop("disabled", true);
to disable the button inside your click handlerHow to increment comment counter
First if commentcounter is in loop it will get the same id that will produce an error you can do one thing that append
@item.Id
with the commentcounter id to make it unique so it should look like commentcounter12 , commentcounter23 if@item.Id = 12 or 23
etc for multiple commentcounters now write this code to increment