Clear Default Search String on Focus

$("#s")
    .val("Search...")
    .css("color", "#ccc")
    .focus(function(){
        $(this).css("color", "black");
        if ($(this).val() == "Search...") {
            $(this).val("");
        }
    })
    .blur(function(){
        $(this).css("color", "#ccc");
        if ($(this).val() == "") {
            $(this).val("Search...");
        }
    });
  1. Set value of field to "Search..."
  2. When field comes into focus, set color to black.
  3. If value is default, remove it.
  4. When field goes out of focus, set color back to light gray.
  5. If value is empty, put back default value

Comments

  1. User Avatar
    Dyllon
    Permalink to comment#

    I would like the text to only go back to grey if it is the default ‘search…’ text..

    blur(function(){
    if ($(this).val() == "") {
    $(this).css("color", "#ccc");
    $(this).val("Search...");
    }

  2. User Avatar
    StuartH
    Permalink to comment#

    This is perfect and has made my day! Thanks.

  3. User Avatar
    simona

    why it doesn’t work for me?
    this is my page
    please take a look, I’m going crazy

    http://www.athenarestauri.com/prova-jquery-2.html

    • User Avatar
      Mike
      Permalink to comment#

      You need to put your jquery functions inside:

      $(document).ready(function(){
      // do jQuery stuff
      })

  4. User Avatar
    Matt
    Permalink to comment#

    @Dyllon

    $(“#searchfield”)
    .val(“Search…”)
    .css(“color”, “#999”)
    .focus(function(){
    $(this).css(“color”, “black”);
    if ($(this).val() == “Search…”) {
    $(this).val(“”);
    }
    })
    .blur(function(){
    $(this).css(“color”, “#999”);
    if ($(this).val() == “”) {
    $(this).val(“Search…”);
    }else if($(this).val() != “Search…”){
    $(this).css(“color”, “black”);
    }
    });

  5. User Avatar
    Heo Chiên Bơ
    Permalink to comment#

    Hi, I’m new to jQuery!
    Sorry for my confusion as I know this can be done quite simple in javascript, just like this:

    --------------
     <form>
    ...
     <input id=string  onFocus="this.form.reset()">
    ...
     </form>
    --------------
    

    Is it much simpler?

Posting Code

You may write comments in Markdown. This makes code easy to post, as you can write inline code like `<div>this</div>` or multiline blocks of code in triple backtick fences (```) with double new lines before and after.

Code of Conduct

Absolutely anyone is welcome to submit a comment here. But not all comments will be posted. Think of it like writing a letter to the editor. All submitted comments will be read, but not all published. Published comments will be on-topic, helpful, and further the discussion or debate.

Want to tell us something privately?

Feel free to use our contact form. That's a great place to let us know about typos or anything off-topic.

Submit a Comment

icon-closeicon-emailicon-linkicon-menuicon-searchicon-tag