[Javascript] Opening an URL through a form

Stone, Timothy tstone at cityofhbg.com
Mon May 5 08:56:37 CDT 2003


> LJ wrote:
> 
> > I'd like to create a HTML form where the word entered in a 
> text field
> > will be added to the following url that will be opened on submit
> > http://www.google.com/search?hl=sv&ie=UTF-8&oe=UTF-8&q=
> > 
> > I.e., if you enter "hello" in the text field submitting the 
> form will
> > open the url 
> http://www.google.com/search?hl=sv&ie=UTF-8&oe=UTF-8&q=hello
> 
> You're in luck -- that's the way browsers work; a 'GET' request
> has all form name/value pairs appended as a 'query string' :-)
> 
> <form method="get" action="http://www.google.com/search">
> <input type="hidden" name="hl" value="sv"/>
> <input type="hidden" name="ie" value="UTF-8"/>
> <input type="hidden" name="oe" value="UTF-8"/>
> <input type="text" name="q"/>
> <input type="submit"/>
> </form>
> 
> In other words, the above form will do exactly what you describe.

LJ,

Are you expecting single term, or one word, searches?

Consider however that, both in practice and expectation, your users are 
likely going to type multiple word phrases!

Further enhance your form by validating your search input. 

If you must force *single word* queries use String.split( delimiter )
to get the first term and pass it to Google.

### in the document head ###

<script language="javascript" type="text/javascript">

// correct user behavior, or force single word searches

function getFirstToken( formArgs ) {
	var query;

	// get an array of query terms passed to Google, tokenized on spaces
	var queryTerms = formArgs.q.value.split( ' ' );

	// get the first term
      query = queryTerms[0];

	// ### begin preview

	// alert( query );
	// return ( false );

      // ### end preview

	return ( formArgs.q.value = query );

}
</script>

### form element: note the onsubmit event handler ###

<form method="get" action="http://www.google.com/search" onsubmit="return getFirstToken( this );">
  <input type="hidden" name="hl" value="sv"/>
  <input type="hidden" name="ie" value="UTF-8"/>
  <input type="hidden" name="oe" value="UTF-8"/>
  <input type="text" name="q"/>
  <input type="submit"/>
</form>

This will correct your user queries, thus meeting your expectations for the form. 

Javascript excels in client side validation of form data before submission to 
server-side applications. But since Javascript can be disabled by the savvy, 
yet paranoid, user make sure that your server-side application revalidates the input. 

In this case you do not have complete control of the server-side application. 
If javascript is disabled, multiple word queries will be passed unvalidated to Google, 
defeating your intended purpose of the form. 

HTH,
Tim


More information about the Javascript mailing list