Tuesday, November 17, 2009

Grails text input field advice trick

To save space and make the user experience a little better, there's a common technique to set a default value in an input text field to guide a user, that gets removed when the user clicks on the input field. This is accomplished like so:

<input name="q" type="text" value="Search" onclick="this.value = ''" />

(clicking in the box would clear the results)

This is nice, but when used as a search input field, it's also nice to re-display to the user what they searched on when the search results are shown in case the user wants to tweak their existing search criteria.

Here's how to add that feature with just a little bit more code in a Grails GSP page.  BTW - you can do the same in other languages, but the syntax will be a little different (e.g. Elvis operators are unique to Groovy).

<input name="q" type="text" value="${params.q ?: 'Search'}" onclick="if (this.value=='Search') {this.value = '';}" />

So now when the search results are displayed, the user will see what they searched on and tweak them if desired.  Nothing mind-blowing, but a nice little pair of features for your users with just a little code.

(clicking in the box won't clear the results)