Change Background color of input field using JavaScript


UPDATED 22 Jul 2020


Method 1:

You can use : .css()

$("#age,#phone").css("background-color","#0F0");

$("input[name='sex']").change(function() {
    if($(this).val() == "female") {
        $("#age,#phone").attr("disabled", true).css("background-color","#0F0");
    } else if($(this).val() == "male") {
        $("#age,#phone").attr("disabled", false).css("background-color","#FFF");;
    }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<input type="radio" name="sex" value="male">Male<br/>
<input type="radio" name="sex" value="female">Female <br/>
Age:<input type="text" name="age" id="age" size="20">
Hobbies:<input type="text" name="hobbies" id="hobbies" size="20"><br/>
Phone:<input type="text" name="phone" id="phone" size="20"><br/>


Method 2:

Another simple way can be using CSS class :

JS:

$("#age,#phone").addClass("green");

CSS:

.green { background-color:#0F0;}

$("input[name='sex']").change(function() {
                var isOptional = $(this).val() == "female";
        $("#age,#phone").attr("disabled", isOptional)
        if(isOptional) $("#age,#phone").addClass("green");
        else $("#age,#phone").removeClass("green");
});
.green{
    background-color:#0F0;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<input type="radio" name="sex" value="male">Male<br/>
<input type="radio" name="sex" value="female">Female <br/>
Age:<input type="text" name="age" id="age" size="20">
Hobbies:<input type="text" name="hobbies" id="hobbies" size="20"><br/>
Phone:<input type="text" name="phone" id="phone" size="20"><br/>


Method 3:

And there is yet another simple way using CSS selector to do so. :

JS:

$("#age,#phone").attr("disabled", true);

CSS:

input:disabled { background-color:#0F0;}

$("input[name='sex']").change(function() {
  $("#age,#phone").attr("disabled", $(this).val() == "female");
});
input:disabled {
  background-color: green;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<input type="radio" name="sex" value="male">Male<br/>
<input type="radio" name="sex" value="female">Female <br/>
Age:<input type="text" name="age" id="age" size="20">
Hobbies:<input type="text" name="hobbies" id="hobbies" size="20"><br/>
Phone:<input type="text" name="phone" id="phone" size="20"><br/>

Refer : https://developer.mozilla.org/en-US/docs/Web/CSS/:disabled