Search code examples
javascriptdynamic-url

Inserting search term into URL not working properly


I am doing a job for a promotional products company. Their products supplier gave me a code to add a search box to their website that searches their database of products and displays results. I altered it to fit my needs, but I'm having an issue where the when you start to fill in the search box, it shows the URL next to the button. any idea how I can fix this?

JS Fiddle

My search field:

<input id="searchTerms" name="searchTerms" type="text" 
       placeholder="Search all Products" />
<a id="reflectedlink" href="http://321987-1d1.espwebsite.com/ProductResults/" 
   onclick="_gaq.push(['_trackEvent', 'Homepage', 'Click', 'Search Button']);">
  <button>Search</button>
</a>

Javascript to insert search term into URL:

var link = document.getElementById('reflectedlink');
var input = document.getElementById('searchTerms');
input.onchange=input.onkeyup = function() {
  link.search = '?searchTerms='+encodeURIComponent(input.value);
  link.firstChild.data = link.href;
};

Solution

  • Why javascript for this? Native HTML form with GET method makes automatically for you:

    <form method="GET" action="http://321987-1d1.espwebsite.com/ProductResults/">
       <input id="searchTerms" name="searchTerms" type="text" placeholder="Search all Products" />
       <button type="submit" onclick="_gaq.push(['_trackEvent', 'Homepage', 'Click', 'Search Button']);">Search</button> 
    </form>
    

    In the moment you push submit button, the URL transforms automatically with the query string parameters.