ASP.Net: Change DIV class based on JSON value returned by jQuery Ajax

smcdevelopments
 
on May 06, 2022 11:09 PM
528 Views

I did some work and couldn't make it to the working conditions.

Posting here to get some help.

In my HTML view, there is a class.

So to get some results I'm using AJAX code and in return according to the result of the JSON value, I want to change the class to another.

This is the code

<div class="stats-small__data">
    <span class="stats-small__percentage" id="SatisPrecent"></span>
</div>

so this span class mainly has,

  1. stats-small__percentage stats-small__percentage--decrease
  2. stats-small__percentage stats-small__percentage--increase

I want to change with the result of ,

if (data.SatisAva > 50) {
   document.getElementById("SatisPrecent").classList.add = 'stats-small__percentage--decrease';
} else {
   document.getElementById("SatisPrecent").classList.add = 'stats-small__percentage--increase';
}

So the current code is not working as I wanted to.

Little help here?

Download FREE API for Word, Excel and PDF in ASP.Net: Download
arjunv
 
on May 07, 2022 07:00 AM

Hi smcdevelopmen...,

Please refer below code sample.

HTML

<div class="stats-small__data">
    <span class="stats-small__percentage" id="SatisPrecent"></span>
</div>
<input type="button" onclick="ChangeClass()" value="Submit" />

<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript">
    function ChangeClass() {
        $.ajax({
            type: "POST",
            url: "Default.aspx/GetData",
            data: '{}',
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (response) {
                $("#SatisPrecent").removeClass();
                if (response.d == 1) {
                    $("#SatisPrecent").addClass("stats-small__percentage--decrease");
                } else {
                    $("#SatisPrecent").addClass("stats-small__percentage--increase");
                }
            }
        });
    }
</script>

Code

C#

[System.Web.Services.WebMethod]
public static int GetData()
{
    int num = 1;
    return num;
}

VB.Net

<System.Web.Services.WebMethod>
Public Shared Function GetData() As Integer
    Dim num As Integer = 1
    Return num
End Function