admin管理员组

文章数量:1201413

I have an input text field, which has a value "something" by default, but when I start to type, I want that the default value changes color, and the text i'll type, another one.

How can i do that?


<input type="text" value="something" onclick="this.value=''" />

I have an input text field, which has a value "something" by default, but when I start to type, I want that the default value changes color, and the text i'll type, another one.

How can i do that?


<input type="text" value="something" onclick="this.value=''" />
Share Improve this question edited Mar 25, 2010 at 15:41 Daniel Vassallo 344k72 gold badges512 silver badges446 bronze badges asked Mar 25, 2010 at 15:21 SimonSimon 23.1k36 gold badges93 silver badges122 bronze badges 1
  • I assume you mean an input text box? A button cannot have text typed into it. – Andy Shellam Commented Mar 25, 2010 at 15:25
Add a comment  | 

5 Answers 5

Reset to default 14

To keep it simple like your example:

<input type="text" value="something" onclick="this.value='';this.style.color='red';" />

And that should pretty much do it.

You may want to try the following:

<input type="text" value="something"
       onFocus="if (this.value == 'something') this.style.color = '#ccc';"
       onKeyDown="if (this.value == 'something') {  
                      this.value = ''; this.style.color = '#000'; }"> 

Going off @chibu's answer, this is how you would do it using jQuery and unobtrusive Javascript


 
$(document).ready(
   function() {
      $("#mytext").bind(
         "click",
         function() {
            $(this).val("");
            $(this).css("color", "red");
         }
      );
   }
)


// 'run' is an id for button and 'color' is for input tag

// code starts here
(function () {
    
    const button = document.getElementById("run");
    button.addEventListener("click", colorChange);

    function colorChange() {
        document.body.style.backgroundColor = document.getElementById("color").value;
    }
})();

Here we go:

<input type="text" value="something" onclick="this.value='';this.style.color='red';" />

Best of luck!

Keep coding!

本文标签: javascriptChange text color in text fieldStack Overflow