JavaScript

Change the Background Color of an Input Field Using JavaScript

While developing websites, most developers prefer to style web pages by changing the text color, background color of a web page, or HTML elements like buttons, input fields, and so on. To do this, developers use CSS. However, there can be a requirement to add styling to web pages using JavaScript. For this purpose, you can utilize the “style.background” CSS property in the JavaScript code.

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:

element.style.backgroundColor = "color"

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:

<h3>Change the Background Color of an Input Field on a Button Click</h3>
<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”:

function color(){
 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:

input.style.backgroundColor = 'rgb(' + 233 + ',' + 185+ ',' + 193 + ')';

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.

About the author

Farah Batool

I completed my master's degree in computer science. I am an academic researcher and love to learn and write about new technologies. I am passionate about writing and sharing my experience with the world.