Tuesday, November 10, 2009

Use SearchControl and SearchForm of Google Search Ajax API

When using the Google Search Ajax API, we may sometimes what to add functions when user initiate a search or clear the search result. the SearchForm is designed to do this. It provides .setOnSubmitCallback(object, method) and .setOnClearCallback(object, method) to let developer define method to call when user search or clear search result. But can we use the SearchControl, which provides easy-to-use and nice wrapped searcher, along with the SearchForm? The answer is yes. Here is the example code of using them together.
function OnLoad() {
var searchControl = new google.search.SearchControl();
searchControl.addSearcher(new google.search.WebSearch());
searchControl.addSearcher(new google.search.ImageSearch());

var drawOptions = new google.search.DrawOptions();
searchControl.draw(document.getElementById("containerResults"), drawOptions);

var searchForm = new google.search.SearchForm(true, document
searchForm.setOnSubmitCallback(searchControl, function() {
searchForm.setOnClearCallback(searchControl, function() {
searchForm.input.value = '';

The HTML code is

< id="searchcontrol">
< id="containerResults">

The point to collect this two part together is drawOptions.setSearchFormRoot(document.getElementById("searchcontrol"));, which tells the SearchControl where to look for the associated SearchForm. Another thing to notice is that, in the SearchForm.SetOnCallBack, the execute() method to call should be the one of the SearchForm, like this.execute(searchForm.input.value);, not the one of the SearchControl (searchControl.execute(searchForm.input.value);), otherwise, the method set to OnClearCallBack will not be called when user clear search result.