Change font color of a form text field with Javascript

What I want is that, with Javascript, when a text is written in a specific text field that the text of this form text field changes color. That is, you can change the color of a text field once the page has been loaded, with javascript as a response to a user event.

To change a CSS style property of a page element with Javascript, there is the style property, which has, among others, the text fields of forms.

Several other attributes depend on the style property, specifically to change the color you have to modify the color attribute.

So the procedure is this:

  • Accessing the text field via the DOM of browser objects
  • On the text field make use of the style property and then the color property.

You can access the DOM in two ways:

1) Access through the form object itself:

It would be a code like this:

document.myform.textfield.style.color=”#00ff00″;

2) Access through your identifier

Another option is to access the form field by its identifier (id attribute):

So to access the input you do document.getElementById(‘idfield’). Once you have the element in a variable, you modify the style as you saw before. The code would be the following:

var field = document.getElementById(‘idfield’); field.style.color=”#00ff00″;

See also  Do all functions in Java require parameters for their implementation?
Loading Facebook Comments ...
Loading Disqus Comments ...