This post will define the method to change the background color of an input field using JavaScript.
How to Change the Background Color of an Input Field Using JavaScript?
Use JavaScript’s “style.background” CSS property to change any element’s background color, such as the input field. A single-color value is utilized to specify the background-color attribute.
Syntax
Follow the given syntax to change the background color of an input field:
In the above syntax, add the color using its name or RGB color code.
Example: Change the Background Color of an Input Field on a Button Click
First, add an input field and a button in the HTML file using the <input> and <button> tags. Attach a click event to the button that will trigger a function called “color()”, which will change the color of the text field when the button is clicked:
<input type="text" id="txt" autocomplete="off"> <br>
<button onclick="color()">Click</button>
After executing the HTML code, the output will be as follows:
In the JavaScript file, first, define the function “color” which will fetch the input field by specifying its id in the “getElementById()” method, and then set the background color to “pink”:
var input = document.getElementById('txt');
input.style.backgroundColor = 'pink';
}
Output
The above GIF shows the input field’s background color is changed when the button is clicked.
Bonus Tip
You can also use the “RGB” values to change the background color as follows:
Output
We have gathered the instructions related to changing the background color of an input field using JavaScript.
Conclusion
For changing the background color of an input field, use the “style.background” CSS property. Using this property, you can set the color of the background attribute using the RGB color code or the color name. This post defined the method for changing the background color of an input field using JavaScript.