Search code examples
javascriptjqueryhtmlgoogle-searchgoogle-custom-search

Issue while calling custom google search tag in javascript


I am using the google custom search api, But I don't want the google search default text box so for the same reson I have craeted a new text box and one button. On click of my custom button I am fetching search key value from my custom text box and putting in to the google search default text box. But in my javascript function I am unable to perform click event of the google search submit button. I know the class name of google search submit button now how can I do the click event in my java script function?

google search dubmit button class name is "gsc-search-button gsc-search-button-v2"

Now in the following method I need to perform the click event of the above class.

<script>
function myFunction() {
   document.getElementById('gsc-i-id1').value = document.getElementById('customTextBox').value;
 // here I need to perform click event for "gsc-search-button gsc-search-button-v2" class
}
</script>script>

I have the demo example in the following link,

http://jsfiddle.net/3L4fd63g/3/

Any suggestions please


Solution

  • I see the tag so heres one option working with a submit of a form so the enter key on the textbox will also perform the search.

    also, to perform a click you just need to call .click()

    // Make sure in jsFiddle you have selected option onLoad.
    (function() {
      var cx = '017643444788069204610:4gvhea_mvga'; // Insert your own Custom Search Engine ID here
      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);
    })();
    
    $(function(){
    
      $('#search').submit(function(e){
        $('.gsc-input').val($('#customTextBox').val());
        $('input.gsc-search-button').click();
        e.preventDefault();
      });
    
    });
    .search-box{
      display:none;
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    
    <form id="search">
      <input type="text" id="customTextBox"/>
      <input type="submit" value="Click me" />
    </form>
    
    <div class="search-box">
        <gcse:searchbox></gcse:searchbox>
    </div>
    
    <gcse:searchresults></gcse:searchresults>