简体   繁体   中英

clear text field value when mouse click

I have three text input fields, like this on jsfiddle .

I put my code here also:

<table>
    <tr>
        <td><input type="text"  value="age" size=30>
        </td>
    </tr>
    <tr>
        <td> <input type="text"  value="Name" size=30>
        </td>
    </tr>
    <tr>
        <td><input type="text"  value="your email" size=30>
        </td>
    </tr>
</table>

css:

input{color:#CCC;}

js:

$('input').click(function() {

            $(this).attr('value', '');
            $(this).css('color','#000');

        }
    });

I would like the mouse click on each field will clear the default value , and when user input value, the text color is black instead of gray.

What I tried is showing on the jsfiddle link. But it does not work, why?

In HTML5, you could use placeholder for this:

<input type="text" placeholder="age" size=30>

Here is the example: http://jsfiddle.net/24n7t/13/

But it only works in modern browsers.

It doesn't work on jsfiddle because you didn't choose to load jQuery (on the left sidebar).

Also, you have an unnecessary bracket ( } ). Remove that and it should work.

Here 'sa working example on jsfiddle.

You have error in jquery code, 1 more curly brace

I remove it use below code

$('input').click(function() {

            $(this).attr('value', '');
            $(this).css('color','#000');

        });

and second thing you included jquery library?? if yes than ok and also include document.ready syntax

语法错误:您还有一个额外的}

Some possible improvements...

$('input[type=text], input[type=password]')   //leave submit buttons, etc alone
  .bind( 'focus', function() {                //focus is more accessible than click
                                              //a user can't change a field without it
      $(this)
         .attr('value', '')                   //more chaining = less searching
         .css('color','#000');
     })
  .bind( 'blur', function() {                 //supposing you want to revert back on blur...
      $(this)
         .css('color','#ccc');
     });

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