Search code examples
javascriptcssasp.netcolorsgetelementbyid

ASP.NET conditional formatting based on value with JavaScript


I am new to both CSS and JavaScript, and I want to change the font color of this section of my .aspx file:

#.aspx
<script src="~/CSS/traffic_lights.js" type="text/javascript"></script> <!-- This handles red/amber/green-->
<div class="Pr">
    <h3>Say what you will about this number:</h3>
    <asp:Label ID="lblResults2" runat="server" Font-Bold="true"></asp:Label>
</div>

My attempt involves adding a .js script to my project where I handle three cases:

#traffic_lights.js

//Red
if (document.getElementById("lblResults2").innerHTML >= 0 &&
    document.getElementById("lblResults2").innerHTML <= 30) {
    document.getElementById("lblResults2").style.color = "red";
}

//Amber (or orange)
if (document.getElementById("lblResults2").innerHTML > 30 &&
    document.getElementById("lblResults2").innerHTML <= 60) {
    document.getElementById("lblResults2").style.color = "orange";
}

//Green
if (document.getElementById("lblResults2").innerHTML > 60 &&
    document.getElementById("lblResults2").innerHTML < 101) {
    document.getElementById("lblResults2").style.color = "green";
}

There is no CSS file specifying which font color should be rendered, so I am not sure why this is not working. The text is always rendered in black, regardless of the numerical value in "Pr".


Solution

  •  <script src="Scripts/jquery-3.3.1.min.js"></script>
    <script>
        $(document).ready(function () {
            var val = parseInt($("#lblResults2").text());
            if (val >= 0 && val <= 30) {
                $("#lblResults2").css("color", "red");
            }
            else if (val > 30 && val <= 60) { $("#lblResults2").css("color", "orange"); }
            else if (val > 60 && val <= 100) { $("#lblResults2").css("color", "green"); }
    
        });
    
    </script>
    
    
    
     <div class="Pr">
    <h3>Say what you will about this number:</h3>
    <asp:Label ID="lblResults2" runat="server" Font-Bold="true" Text="99" ClientIDMode="Static"></asp:Label>
    

    you can change 'Text' attribute of asp:label