Changing CSS With JQuery On Change


Changing CSS With JQuery

JQuery makes it very simple to alter css properties for an element, id, or class. The code below shows how an input value can become orange in case the number is greater than 10.

Initially, the change() function is activated when an input field changes. It is similar to Javascript's onchange attribute. Then, the value is stored as an object with $(this).val() and the class is stored as an object $(this).attr('class').  Now, conditional statements are used to change the css text color if the value of a given input box becomes greater than 10. If it becomes greater than 10 the text becomes orange. If the text is 10 or less it becomes black. The full code is given below.

$(document).ready(function(){

    $("input").change(function() {

    var myvalue = $(this).val();
    var myattributenclass = $(this).attr('class');
    
    if(myvalue > 10 && myattributenclass == "class1"){
        $(this).css("color", "#dc4000");
    }    
    else {
    $(this).css("color", "#000000");
    }
    
    if(myvalue > 10 && myattributenclass == "class2"){
        $(this).css("color", "#dc4000");
    }
    else {
    $(this).css("color", "#000000");
    }
    
    if(myvalue > 10 && myattributenclass == "class3"){
        $(this).css("color", "#dc4000");
    }
    else {
    $(this).css("color", "#000000");
    }
    
    if(myvalue > 10 && myattributenclass == "class4"){
        $(this).css("color", "#dc4000");
    }
    else {
    $(this).css("color", "#000000");
    }
    
    if(value > 10 && myattributenclass == "class5"){
        $(this).css("color", "#dc4000");
    }
    else {
    $(this).css("color", "#000000");
    }
    
    });
});