Search code examples
javascriptgoogle-custom-search

Multiple Google CSE (Custom Search Engine) Boxes on Same Page


I am trying to implement two (different) Google CSE search boxes on the same page. The issue is that only the first instance works properly. For example, a sitewide search box in the header, then on certain pages, a 2nd search box that searches within a narrow silo of the site, etc.

This doesn't work properly in that with using the google-generated code for each box, they both get the same form ID, which is obviously not valid. This causes the google watermark branding to fail to appear in box #2, and also some auto/google generated variables fail to generate for the 2nd box also, such as the ss parameter (search session).

Now, the search itself works in both boxes, e.g. user searches, is taken to correct results page, and correct results are shown.

I am just trying to resolve this issue: how can I cause the 2nd form to get a different ID value (and still work properly - as google's javascript looks for the ID cse-search-box) I have tried adding a unique identifier to the ID and NAME attributes of the <form> element, but that caused the google.com javascript to malfunction (as I believe it looks for `cse-search-box' only)

Code is as follows:

search box 1:

<form id="cse-search-box" name="cse-search-box" class="search searchHeader" method="get" action="/search">
<input type="hidden" name="cx" value="partner-pub-0000000000000000:000" />
<input type="hidden" name="cof" value="FORID:10" />
<input type="hidden" name="ie" value="UTF-8" />
<input type="text" name="q" id="q" class="text_input" />
<input type="submit" name="sa" value="Search" class="submit" />
</form>
<script type="text/javascript" src="http://www.google.com/coop/cse/brand?form=cse-search-box&amp;lang=en"></script>

search box 2:

<form id="cse-search-box" name="cse-search-box" class="search searchWebDirectory" method="get" action="/search">
    <input type="hidden" name="cx" value="partner-pub-0000000000000000:111" />
    <input type="hidden" name="cof" value="FORID:10" />
    <input type="hidden" name="ie" value="UTF-8" />
    <input type="text" name="q" id="q" class="text_input" />
    <input type="submit" name="sa" value="Search" class="submit" />
</form>
<script type="text/javascript" src="http://www.google.com/coop/cse/brand?form=cse-search-box&amp;lang=en"></script>

Solution

  • From: http://www.google.com/cse/docs/cref.html

    The parameter in /coop/cse/brand named "form" outputs the first getElementById in the code. As such, using http://www.google.com/coop/cse/brand?form=cse-search-box&lang=en will create a cse-search-box-targetted code, whilst giving it box2 will trigger on a different ID. The keyword searchbox_demo is reserved.

    Give it a go if you'd like to: http://jsfiddle.net/JTV6f/1/ . Considering what you are doing, however, if I were you, I'd switch to either the V1 or V2 APIs.