April 25, 2011

How can I clear the input text.. when I clicked

Question by psygnosis

How can I clear inputttext..when I clicked the input text with jquery… no change.. I mean

example I have a input text and is value TEXT..

When I clicked the input text value is empty..

Answer by David Thomas

To remove the default text, on clicking the element:

$('input:text').click(
    function(){
        $(this).val('');
    });

I would, though, suggest using focus() instead:

$('input:text').focus(
    function(){
        $(this).val('');
    });

Which responds to keyboard events too (the tab key, for example). Also, you could ue the placeholder attribute in the element:

<input type="text" placeholder="default text" />

Which will clear on focus of the element, and reappear if the element remains empty/user doesn’t input anything.

Answer by Starx

I am supposing you are trying to create a effect, where the textbox contains a label. And when the user click in the textbox, it disappears and lets the user input the text. You do not require Jquery for this.

<input type="text" value="Input Text" onfocus="this.value=''" onblur="(this.value=='')? this.value='Input Text':this.value;" />

Demo

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!