Submit Google Custom Search with Jquery

2019-09-19 09:01发布

问题:

Im using Google custom search and I would like to submit its form using my own div with Jquery. I tried many things with no luck, this is one of them:

The Google code:

<script>
  (function() {
    var cx = 'partner-pub-2789521296837340:9402765321';
    var gcse = document.createElement('script');
    gcse.type = 'text/javascript';
    gcse.async = true;
    gcse.src = (document.location.protocol == 'https:' ? 'https:' : 'http:') +
        '//www.google.com/cse/cse.js?cx=' + cx;
    var s = document.getElementsByTagName('script')[0];
    s.parentNode.insertBefore(gcse, s);
  })();
</script>


<gcse:search></gcse:search>

The Jquery part:

$( document ).ready(function() {

$( "div.button" ).click(function() {
  $( "form.gsc-search-box" ).submit();
    return false;
});


});

Live example: JsFiddle

回答1:

We cannot submit form (i.e., Google created internally using jQuery) directly. You have to change your code to change look and feel. Here is the one you are looking for:

<form id="cse-search-box" action="http://google.com/cse">
  <input type="hidden" name="cx" value="YOUR SEARCH ENGINE ID goes here" />
  <input type="hidden" name="ie" value="UTF-8" />
  <input type="text" name="q" size="31" />
  <input type="submit" name="sa" value="Search" />
</form>
<img src="http://www.google.com/cse/images/google_custom_search_smwide.gif">

Reference: https://support.google.com/customsearch/answer/1351747?hl=en

DEMO FIDDLE