Chuck Le Butt
Chuck Le Butt

Reputation: 48798

Empty input box onclick in jQuery

I've no idea why this isn't working, but I'm sure it's a very common bit of Javascript. My syntax is clearly lacking, and I don't know why:

<input type="text" value="search" id="search" name="q" onclick="javascript:if($(this).val() == 'search') {$(this).val() = '';} return false;" />

Upvotes: 9

Views: 59164

Answers (8)

Vishal Vaghasiya
Vishal Vaghasiya

Reputation: 2104

You can clear the input field by using

$(this).val('');

Upvotes: 0

Jarown
Jarown

Reputation: 11

This has become easier with a HTML5 Placeholder:

<input type="text" name="search" placeholder="Enter your search query here">

It's not supported in older browsers, but if you're only targeting modern ones, you should be fine to use it: http://caniuse.com/#feat=input-placeholder

Upvotes: 1

Vimalnath
Vimalnath

Reputation: 6463

It should be like this:

<input type="text" value="search" id="search" name="q" onclick="javascript:if($(this).val() == 'search') {$(this).val('');} return false;" />

correct way   : $this.val('');
incorrect way : $this.val() = '';

Upvotes: 3

Tom
Tom

Reputation: 12998

Put this in a separate js file...

this will return it to the initial value if nothing is typed after it loses focus.

$(document).ready( function() {
    $("#search").focus( function() {
        if ( $(this).val()=="search") {
            $(this).val('');
        } 
    });

    $("#search").blur( function() {
        if ( $(this).val()=="") {
            $(this).val('search');
        } 
    });
});

Upvotes: 4

Flash
Flash

Reputation: 16743

$(this).val() = '';

should be

$(this).val('');

See .val() documentation.

Upvotes: 2

James Hill
James Hill

Reputation: 61832

Your issue is with this line of code:

$(this).val() = ''

The proper way to set a value in jQuery is:

$(this).val("Your value here");

In addition, inline JS is never a good idea. Use this instead:

$("#search").on("click", function() {
    if ($(this).val() == "search")
        $(this).val("")
});​

Here's a working fiddle.

References: jQuery .val()

Upvotes: 15

dhinesh
dhinesh

Reputation: 4764

function search(textBox)
{
   if($(textBox).val() == 'search') {
        $(textBox).val() = '';
   } 
   return false;
}

<input type="text" value="search" id="search" name="q" onclick="return search();" />

Try this and debug.

Upvotes: -2

themhz
themhz

Reputation: 8424

no you need $(this).val(""); or $(this).val(''); to empty it

<input type="text" value="search" id="search" name="q" onclick="javascript:if($(this).val() == 'search') {$(this).val('');} return false;" />

Upvotes: 0

Related Questions