views:

67

answers:

2

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.

A: 

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:

Daniel Vassallo
A: 

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.

Kevin Won
maybe add an example css class declaration that sets the properties the OP was asking about...
davidsleeps