Form: Making search text disappear onclick

I’d like the text in the search box to disappear when the box is clicked in. Easy, right? I’ve found several how-to pieces online, and gotten it to work with at least two different methods. However, I found a [URL=“http://bytes.com/topic/html-css/answers/155272-making-default-entry-search-text-box-disappear-click”]rather snotty discussion of form semantics that made me wonder: what’s the right way to accomplish this, can I tighten up this code to be clean and tidy, and most importantly, can someone explain it to me so I can understand it? :lol: Forms tend to leave me confrazzled.

The site link’s above but here’s the code:

[highlight=“HTML 4.01 Strict”]<form method=“get” action=“http://www.google.com/search” id=“search”>
<div>
<div class=“qkinsearch-box”>
<label for=“mainsearchbox”>Search Site</label>
<input type=“hidden” name=“ps” value=“10”>
<input type=“text” size=“15” class=“search-field” name=“s” id=“mainsearchbox” value=“search amy’s site” onfocus=“if(this.value == ‘search amy’s site’) {this.value = ‘’;}” onblur=“if (this.value == ‘’) {this.value = ‘search amy’s site’;}”>
<input type=“submit” value=“” class=“search-go”>
</div>
</div>
</form>



Possibly relevant CSS:


```css
/*** search form ***/
form#search {
 float: right;
 width: 32em;
 margin-top: -4.75em;
 margin-right: .5em;
 font-family: "Liberation Sans", "Lucida Grande", "Lucida Sans", Helvetica, Arial, sans-serif;
}

form#search input {
 font-family: "Liberation Sans", "Lucida Grande", "Lucida Sans", Helvetica, Arial, sans-serif;
}

form#search label {
 position:absolute;
 left:-999em;
}

form#search input#mainsearchbox {
 font-family: "Liberation Sans", "Lucida Grande", "Lucida Sans", Helvetica, Arial, sans-serif;
}

.qkinsearch-box {
 background:url(../images/search/search-box.gif) no-repeat top left;
 height: 26px;
 padding: 5px 0 0 10px;
 width: 165px;
 margin-right: 20px;
 float:right;
 display:inline;
}

input.search-field {
 float: left;
 border:0;
 margin:0;
 font-family: Tahoma, Arial, sans-serif;
 font-size: 12px;
 padding: 3px 0px 1px 4px;
 height:17px;
 background: #fff url(../images/search/search-form.png) no-repeat 100&#37; 0;
 width: 123px;
 color: #a8a8a8;
}

input.search-go {
 float:left;
 border:0;
 margin:0;
 padding:0;
 margin-left: 7px;
 height: 21px;
 width: 21px;
 background: url(../images/search/search-icon.png) no-repeat top left;
 cursor: pointer;
}

input.search-go:hover {
 background:url(../images/search/search-icon.png) no-repeat bottom left;
}

I’m quite sure there are some redundant and useless elements in both the HTML and CSS, but I’m not sure what should be left out, what should remain, and what should be edited.

Note: This search isn’t functional yet. I haven’t secured a URL for the client yet, and therefore haven’t put in for a Google search account for her. So those critical elements are definitely missing.

You can either use a simple bit of code like this:

value="search amy's site" onfocus="if(this.value == 'search amy's site'){this.value = '';}"

or use a proper script that is unobtrusive (this one courtesy of Jeremy Keith):


function addLoadEvent(func) {
  var oldonload = window.onload;
  if (typeof window.onload != 'function') {
    window.onload = func;
  } else {
    window.onload = function() {
      oldonload();
      func();
    }
  }
}

function resetFields(whichform) {
  for (var i=0; i<whichform.elements.length; i++) {
    var element = whichform.elements[i];
    if (element.type == "submit") continue;
    if (!element.defaultValue) continue;
    element.onfocus = function() {
    if (this.value == this.defaultValue) {
      this.value = "";
     }
    }
    element.onblur = function() {
      if (this.value == "") {
        this.value = this.defaultValue;
      }
    }
  }
}

function prepareForms() {
  for (var i=0; i<document.forms.length; i++) {
    var thisform = document.forms[i];
    resetFields(thisform);
    thisform.onsubmit = function() {
      return validateForm(this);
    }
  }
}

addLoadEvent(prepareForms);

and most importantly, can someone explain it to me so I can understand it?

Unfortunately not! I’m gradually getting my head around it, but I recommend Jeremy Keith’s DOM Scripting book if you really want a proper explanation. :slight_smile:

Ralph, this code snippet:

value="search amy's site" onfocus="if(this.value == 'search amy's site'){this.value = '';}"

is exactly what’s in the site now. :slight_smile:

On the upside, the JS snippet works nicely. I’d still like to know more about how to make that form code more efficient (i.e. are there elements in the HTML I can strip out or streamline, are there conflicting elements in the CSS, etc), but this is one answer to my most immediate question.

Thanks! :cookie:

Yeah, I really advocate the structure of DOM Scripting. Jeremy Keith is an excellent teacher!

Once you wrap your head around the core, you will appreciate the simplicity of jQuery.

/*** Search ***/
function search(obj) {
	$(obj).blur(function() {
		if (this.value == "") { 
			this.value = "Search";
		}
	});
	
	$(obj).focus(function() {
		if (this.value == "Search") {
			this.value = "";
		}
	});
}

There’s not enough ibuprofen in the world to get me through learning this… Of course, I said that about HTML/CSS, too.

I don’t know what the HTML is supposed to be for that Jeremy Keith, but for a simple search form the JS can be simpler.


      <form action="" method="get" id="formSearch">
        <div>
          <input type="text" name="search" title="search our site" value="">
          <input type="submit" value="Search">
        </div>
      </form>

    <script type="text/javascript">
      var searchLabel = document.forms["formSearch"]["search"];
      searchLabel.value = "typ uw trefwoorden in";
      searchLabel.onfocus = function() {
        searchLabel.select(); //highlights on focus
        //or this.value=''; removes value on focus
      }
    </script>

The particular form above used the value text instead of a label… so title text was provided for screen readers. Since it was one of those “obvious” search forms, the lack of a label or lack of value text didn’t make it harder to use… as those without JS aren’t getting the value text in the first place. So, not acceptable for forms where the input value is supposed to explain what to do in non-obvious forms.

That way folks like me don’t have to backspace through them all : )

Poes, I’ll give that a try … without the “typ uw trefwoorden in” stuffz. :smiley:

Type Your Keywords In

: )

I don’t quite understand your point, poes. That code you gave doesn’t seem to display default input text. What is the JS for? Have I missed something?

The Keith code is for a simple form. It goes on a bit because he likes to cover all bases before messing with the DOM. There is more to his code… I just stripped it down for the current purpose, and maybe left in more than I needed to.

Actually ralph I never tested beyond my Linux browsers, so possibly you’ve found a browser bug? It works in FF, Chrome, Opera and Konq on Linux.
searchLabel.value = “typ uw trefwoorden in”;
sets the value of the input to “type uw trefwoorden in” when the script is loaded. Right now, with the second-to-last line uncommented, onfocus or onclick will highlight the text for easy deletion… comment that line out and uncomment the last line instead and it clears the value entirely.

The Jeremy Keith one has an event loader (so his can be kept off the page) and also seems to have something to validate the form but I don’t know what it’s validating. It looks like it’s part of a greater form script that does a bunch of stuff.
Mine’s written ONLY for a search form (so we don’t loops through inputs because there’s only one + submit) and it ONLY deals with the text. It doesn’t do form validation or check for other things and the way I posted it, it needs to sit on the page (it could be moved off the page but then it would need Keith’s event listener).
Mine’s very very restrictive. It does just one thing. If lots of form stuff is going on on the page then I’d rather either have the Jeremy Keith one or maybe a library like Cooper posted, but if it’s all on its lonesome and only does just one little thing, I prefer one tiny script.

Yes, sorry Stomme poes, I didn’t quite use your code as you posted it, so my fault. Once I place the JS after the form it worked. I just prefer not to do that if I can help it.

And yes, the Keith code was really for a longer form, with multiple inputs, and included some separate validation code that I obviously didn’t strip out entirely. It was a quick hack job.

I just prefer not to do that if I can help it.

This is usually also true for me… feels like polluting the HTML with scripts.

This would become very cumbersome pretty fast if you have many input fields. I would recommend comparing it with ‘defaultValue’ attribute. That way one tiny script will work for all input fields.

This would become very cumbersome pretty fast if you have many input fields.

Once the spec changes to “many input fields” then yes, something completely different should be used.

Though I do have to say, Search is prolly the one form where I usually see pre-written text in the input. I don’t see it too often in long forms. Those are smarter: they have real labels.