简体   繁体   中英

Change color of textbox in JavaScript

I have this small JavaScript code which I need some help with:

function doFocus(text) {
    if (text.value == "Enter Name") {
       text.value = "Student Name -";
    }
}

All I need here is when someone clicks on my textbox, the text "Student Name -" should change its color, and should text-align = left. I am looking for the appropriate syntax for something like text.color and text.align.

Assuming text is the DOM element, you may want to try the following:

function doFocus(text) {
   if (text.value === 'Enter Name') {
       text.value = 'Student Name -';
       text.style.color = 'red';
       text.style.textAlign = 'left';
   }
}

If you are using this to place a watermark in your text field, you may also be interested in checking out the following Stack Overflow post:

I'd change the style or class attribute to do it in CSS probably.

// JS pseudocode just to get the idea across
var textBox = getTheTextBox();
if (textBox.value == "bla")
{
    // use JS framework like JQuery to change the css class
    textBox.class('highlight'); 
}

I'm guessing for the example you didn't show your JS using JQuery or some other framework, but just in case you haven't got the religion, I'd also suggest using a JS framework such as JQuery to assist in the DOM manipulation.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM