Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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;" />
like image 366
Chuck Le Butt Avatar asked Mar 19 '12 12:03

Chuck Le Butt


2 Answers

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() = '';
like image 86
Vimalnath Avatar answered Sep 25 '22 09:09

Vimalnath


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

like image 45
James Hill Avatar answered Sep 24 '22 09:09

James Hill