Change Background color of input field using JavaScript
I am making a form and making input field to read only using JavaScript. I want to change the default color for read only attribute to green or yellow.
HTML
<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/>
When someone click on female the input having Id's "age" and "phone" becomes reading only using JavaScript.
JS
$(function() {
$("input[name='sex']").change(function() {
if($(this).val() == "female") {
$("#age").attr("disabled", true);
style="backgroundcolor=green"
$("#phone").attr("disabled", true);
} else if($(this).val() == "male") {
$("#age").attr("disabled", false);
$("#phone").attr("disabled", false);
}
});
});
I want to change the color of input field when it is read only.
Just use : .css()
Sample : http://jsfiddle.net/cL7ngmda/
$("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");
}
});
Another simple way can be using CSS class : http://jsfiddle.net/e83s7s80/7/
css
.bg-green{
background-color:green;
}
js
$("input[name='sex']").change(function() {
$("#age,#phone").attr("disabled", $(this).val() == "female").toggleClass("bg-green");
});
And there is yet another simple way using CSS selector to do so. : http://jsfiddle.net/dqgqjya5/3/
Just add this css :
input:disabled{
background-color:green;
}
js
$("input[name='sex']").change(function() {
$("#age,#phone").attr("disabled", $(this).val() == "female");
});
Refer : https://developer.mozilla.org/en-US/docs/Web/CSS/:disabled
$("#age").css('background-color', 'green');
要么
$(this).css('background-color', 'green');
你可以试试这个:
$("input[name='sex']").change(function () {
if ($(this).val() == "female") {
$("#age").attr("disabled", true);
$("#age, #hobbies, #phone").css("background-color", "green");
$("#phone").attr("disabled", true);
} else if ($(this).val() == "male") {
$("#age").attr("disabled", false);
$("#phone").attr("disabled", false);
$("#age, #hobbies, #phone").css("background-color", "white");
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.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/>
链接地址: http://www.djcxy.com/p/70512.html
上一篇: 如何禁用背景