Add CSS class to Anchor Link on Click using jQuery in ASP.Net

Last Reply 7 months ago By dharmendr

Posted 8 months ago

how to add css class to button with onclick function on a table row using ajax json.

Display Image in Bootstrap Modal Popup based on Table row selection using jQuery in ASP.Net

 

<script type="text/javascript">
    $(function () {
        GetProduct();
    });
 
    function Getproductname(ele) {
        $(ele).html($(ele).closest('div').find('.sproductname').html());
        $(".modal-body #lblName").html("Id is :" + $(ele).data('id') + " Name is : " + $(ele).closest('div').find('.sproductname').html());
         $('#img1').attr('src', $(ele).closest('div').find('.strcimg').attr('src'));//code for image display
        $(".modal-body #lblName").css("color", "red");
   	$(ele).closest('div').find('.btnclass1').addClass('activatecss1');//i changed the code here...this code works fine now for me
    }
    function GetProduct() {
        $.ajax({
            type: "POST",
            contentType: "application/json; charset=utf-8",
            url: "WebService.asmx/GetData",
            data: {},
            dataType: "json",
            success: function (data) {
                var table = $('#tblgrid');
                var rows = "";
                for (var i = 0; i < data.d.length; i++) {
                    rows += "<div class=trclass>" +
                        "<tr><td class=tdcolumn>" +
                        "<div class=tablediv>" +
                        "<div class=Productid>" + data.d[i].ProductId + "</div>" +
                        "<div class=sproductname>" + data.d[i].ProductName + "</div><br />" +
                        "<div class=sproductname>" + data.d[i].ProductQty + "</div><br />" +
                        + ' <img class=pdtimg src="images/loader.gif" data-echo="data:image/jpg;base64,' + data.d[i].Pimage + '" />'               
                        "<div class=sproductname>" + data.d[i].ProductType + "</div><br />" 
                        += '<p><a class=" btn btnclass1"  onclick=Getcouponcode(this) data-id="' + data.d[i].Productid + '"  id=btn1 role="button" target="_blank" data-toggle="modal">click</a></p>'
                        "</div></td></tr></div>"
                }
                table.append(rows);
            },
            failure: function (response) { alert(response.d); },
            error: function (response) { alert(response.d); }
        });
    }
</script>

 

.activatecss1{
    background-color: white;
}

 

Posted 7 months ago

Hi jovceka,

jovceka says:
$(ele).closest('div').find('.btnclass1').addClass('activatecss1');

Change the above code with the below.

$(ele).addClass('activatecss1');

Check this example. Now please take its reference and correct your code.

HTML

<div>
    <div class="modal fade" id="DesPopUp" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">&times;</span></button>
                </div>
                <div class="modal-body" id="listOfNotes">
                    <p>Some text in the modal.</p>
                    <asp:Label ID="lblName" runat="server" />
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
                </div>
            </div>
        </div>
    </div>
</div>
    <style type="text/css">
    .activatecss1
    {
        background-color: #0090CB;
        color: White;
    }
</style>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript" src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" />
<script type="text/javascript">
    $(function () {
        GetProduct();
    });

    function Getproductname(ele) {
        $(ele).html($(ele).closest('div').find('.sproductname').html());
        $(".modal-body #lblName").html("Id is :" + $(ele).data('id') + " Name is : " + $(ele).closest('div').find('.sproductname').html());
        $(".modal-body #lblName").css("color", "red");
        $(ele).addClass('activatecss1');
    }
    function GetProduct() {
        $.ajax({
            type: "POST",
            contentType: "application/json; charset=utf-8",
            url: "WebService.asmx/GetData",
            data: {},
            dataType: "json",
            success: function (data) {
                var table = $('#tblgrid');
                var rows = "";
                for (var i = 0; i < data.d.length; i++) {
                    rows += "<div class=trclass>" +
                        "<tr><td class=tdcolumn>" +
                        "<div class=tablediv>" +
                        "<div class=Productid>" + data.d[i].ProductId + "</div>" +
                        "<div class=sproductname>" + data.d[i].ProductName + "</div><br />" +
                        '<p><a class="btn btnclass1" target="_blank" onclick = Getproductname(this) data-id="' + data.d[i].ProductId + '" id=btnDeal role="button" data-toggle="modal" data-target="#DesPopUp" >submit</a></p>' +
                        "</div></td></tr></div>"
                }
                table.append(rows);
            },
            failure: function (response) { alert(response.d); },
            error: function (response) { alert(response.d); }
        });
    }
</script>

WebService

C#

using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Web.Services;
 
/// <summary>
/// Summary description for WebService
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
[System.Web.Script.Services.ScriptService]
public class WebService : System.Web.Services.WebService
{
    [WebMethod]
    public Products[] GetData()
    {
        List<Products> details = new List<Products>();
        string conString = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
        string query = "SELECT TOP 5 ProductId,ProductName FROM Products ORDER BY ProductId ASC";
        SqlCommand cmd = new SqlCommand(query);
        using (SqlConnection con = new SqlConnection(conString))
        {
            using (var sda = new SqlDataAdapter())
            {
                DataTable TableData = new DataTable();
                cmd.Connection = con;
                sda.SelectCommand = cmd;
                TableData.Clear();
                sda.Fill(TableData);
                foreach (DataRow dtrow in TableData.Rows)
                {
                    Products user = new Products();
                    user.ProductId = Convert.ToInt32(dtrow["ProductId"].ToString());
                    user.ProductName = dtrow["ProductName"].ToString();
                    details.Add(user);
                }
            }
        }
 
        return details.ToArray();
    }
 
    public class Products
    {
        public int ProductId { get; set; }
        public string ProductName { get; set; }
    }
}

VB.Net

Imports System.Collections.Generic
Imports System.Configuration
Imports System.Data
Imports System.Data.SqlClient
Imports System.Web.Services
 
' To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
<System.Web.Script.Services.ScriptService()> _
<WebService(Namespace:="http://tempuri.org/")> _
<WebServiceBinding(ConformsTo:=WsiProfiles.BasicProfile1_1)> _
<Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> _
Public Class WebService
    Inherits System.Web.Services.WebService
 
    <WebMethod()>
    Public Function GetData() As Products()
        Dim details As List(Of Products) = New List(Of Products)()
        Dim conString As String = ConfigurationManager.ConnectionStrings("constr").ConnectionString
        Dim query As String = "SELECT TOP 5 ProductId,ProductName FROM Products ORDER BY ProductId ASC"
        Dim cmd As SqlCommand = New SqlCommand(query)
        Using con As SqlConnection = New SqlConnection(conString)
            Using sda = New SqlDataAdapter()
                Dim TableData As DataTable = New DataTable()
                cmd.Connection = con
                sda.SelectCommand = cmd
                TableData.Clear()
                sda.Fill(TableData)
                For Each dtrow As DataRow In TableData.Rows
                    Dim user As Products = New Products()
                    user.ProductId = Convert.ToInt32(dtrow("ProductId").ToString())
                    user.ProductName = dtrow("ProductName").ToString()
                    details.Add(user)
                Next
            End Using
        End Using
 
        Return details.ToArray()
    End Function
 
    Public Class Products
        Public Property ProductId As Integer
        Public Property ProductName As String
    End Class
 
End Class

Screenshot