9

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;" />

8 Answers 8

15

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()

Sign up to request clarification or add additional context in comments.

Comments

4

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');
        } 
    });
});

1 Comment

This is also great, I actually wrote the same code after James's answer. Thanks, though!
3

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() = '';

Comments

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

should be

$(this).val('');

See .val() documentation.

Comments

1

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

1 Comment

The placeholder attribute does indeed make this much easier (provided your browser supports it), but you should avoid just posting links as answers. Links have a tendency to rot and disappear. The main content should be posted into your answer.
0

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;" />

Comments

0

You can clear the input field by using

$(this).val('');

Comments

-2
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.