-1

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;
};
thanksd
  • 54,176
  • 22
  • 157
  • 150
Paul Ruocco
  • 462
  • 3
  • 18

4 Answers4

0

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.

Marcos Pérez Gude
  • 21,869
  • 4
  • 38
  • 69
  • The JS version is what was supplied to me. I opted not to mess with it too much because I didn't know enough about it. This works well though. Thanks. – Paul Ruocco Jan 14 '16 at 17:00
0
link.firstChild.data= link.href;

This line put the link href as text content inside the link. If you don’t want that, remove this line.

CBroe
  • 91,630
  • 14
  • 92
  • 150
0

change

link.search= '?searchTerms='+encodeURIComponent(input.value);

to

link.href= '?searchTerms='+encodeURIComponent(input.value);

ZagNut
  • 1,431
  • 15
  • 20
0

This is appending the URL text:

link.firstChild.data= link.href;

Delete it or comment it out--or use Marcos' suggestion above, which is a simpler and more typical solution.

James
  • 1,568
  • 1
  • 15
  • 25