How can I addClass this Button in OnClientClick event.
I have a list of 2 buttons:
<asp:Repeater ID="rpt_one" runat="server" ClientIDMode="Static">
<ItemTemplate>
<asp:Button ID="bt_falist" ClientIDMode="Static" OnClientClick='<%# "handleLikeClick("11", "22"); return false;" %>' Text="" />
<label id="countlike"><%# Eval("CountF") %></label>
</ItemTemplate>
</asp:Repeater>
I try to addClass for button’s event. However when I click on the 2nd button it addsClass to the first button
function handleLikeClick(videoId, id) {
// Perform your like button logic here
/*alert(videoId);*/
$.ajax({
type: "POST",
url: "...",
data: JSON.stringify({ videoId: videoId, id: id }),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
//$(this).addClass("fas colorred");
$('#bt_falist').addClass("fas colorred");
$('#bt_falist').removeClass("far");
var txt = document.getElementById("countlike").innerHTML;
var num = parseInt(txt) + 1;
document.getElementById("countlike").innerHTML = num;
},
error: function (error) {
alert(error.responseText);
}
});
// Prevent postback
return false;
};
Even though I try to use: $(this).addClass()
but it still gives the same result.
Looking forward to a solution. Thank you
2
Answers
The issue is that both the button have the same ID. To solve the issue, you can use class attribute like the following way:
HTML:
JS:
For a gridview, repeater, listview etc.?
Then for repeating controls, each control (with runat=server) will receive a custom ID. This is required, since then how would you know or distinguish the difference between controls on each row? And you can’t have on a page multiple controls with the same id – that’s not allowed.
The most simple way is to PASS the current button in your function.
So, then this:
So, now in your function, you can do this:
So, pass the button via "this".
Remember, a button or ANY control in a data repeater (repeater, listview, gridview) will be given a row number. In fact in most cases it will be given the control name, button name, and then row number.
So the button id becomes GridView_myButtonid_01 etc.
But, you don’t have to much care, since passing this will solve that issue.