Search code examples
javascripthtmlcsssearch-engine

Why use an extra input element to create a internal web site search box (and)


Why am I using, or need to use the extra input element with the attribute of hidden to make a web site search box that searches the given web site internally.

<div id="search_box">
<form name="searchform" action="http://www.google.com/search" method="get" target="_blank">
<input name="sitesearch" type="hidden" value="www.example.com" />
<input name="as_q" onfocus="this.value=''" type="text" size="20" value="Search www.example.com" title="Enter your search here" />
<input title="Begin Search" type="submit" value="Search" />
</form>
</div>

Additionally do I really need to use Javascript onfocus="this.value=''" to clear the text/value of "Search www.example.com" once the user has clicked on it. Why does this not work which I suspect is due to the fact that one can not "target" some "attribute" via. CSS and there are no "alternative" CSS properties for a given HTML attribute.

input[type="text"]:focus
{
value: "";
}

The above will fail as I can not (or can I?) target the value attribute! But it just seems an overkill to use Javascript for a very small functionality like this one. Almost like using JS for hover effects rather than CSS pseudo:hover.


Solution

  • Why am I using, or need to use the extra input element with the attribute of hidden to make a web site search box that searches the given web site internally.

    Somehow you must tell the search engine that you want to limit the search to a specific site. Normally this is done via a hidden input field, since that gets included when the form is submitted but not show to the user.

    However it doesn't need to be a hidden element. You can put it in a text, radiobutton, checkbox or select too. The only requirement is that it is sent to the search engine with name "sitesearch" and with a value with the website of your choice.

    do I really need to use Javascript onfocus="this.value=''" to clear the text/value of "Search www.example.com" once the user has clicked on it.

    You can set value='' from the beginning and use the new html5 attribute placeholder='Search www.example.com'. Or use a descriptive text somewhere on the page.

    But it just seems an overkill to use Javascript for a very small functionality like this one. Almost like using JS for hover effects rather than CSS pseudo:hover.

    You might think of it as overkill, but for years it was the only way to do it. Javascript has been in the browsers long before CSS was implemented. The hover effect had to be implemented in javascript because :hover wasn't introduced until CSS2. The placeholder effect that you want to use in this case has only recently been implemented with HTML5.