[home] [PDF Version]
Sometimes you'll want to offer users the abilty to search your site, without having to set up a search engine yourself. The good news is that google can do this for you, with a little tweaking.
Putting a google search box on your page is pretty straight forward:
<form action="http://www.google.com/search" method="get"> Search: <input type="text" name="q"> <input type="submit" value="Go"> </form>
This box allows users to search for anything on google - not quite the effect you want. Luckily, google has a built-in syntax for showing only matches from a single site. By putting in the query "site:www.foo.com bar", you only get matches for pages containing "bar", on the website at www.foo.com.
You could ask users to type in "site:www.yourdomain.com" before their queries, but this is inelegant, so you can use a piece of javascript to automatically add that on to the beginning of the query:
<form action="http://www.google.com/search" method="get" onsubmit="this.q.value = 'site:www.domain.com ' + this.query.value;"> <input type="hidden" name="q"> Search: <input type="text" name="query"> <input type="submit" value="Go"> </form>
Now, when the form is submitted, the value from the "query" field is taken, the "site:" pragma is prepended to it, and the result is put in the hidden field "q", ready for google to use.