How should I structure the following link so that the value of SearchInput is added as a parameter?
Thanks
<input id="SearchInput" name="SearchInput" type="text" aria-label="Search Input" />
<a href="/search?term="[value from input]>SEARCH</a>
I was thinking something like this
<a href="#" onclick="this.href = '/search?term=' + document.getElementById(SearchInput).value">
>Solution :
Your proposed solution looks almost correct, but you need to enclose SearchInput
within quotes since it is an ID selector. Also, you can prevent the default behavior of the anchor element by returning false at the end of the onclick function. Here’s an updated version of the code:
<input id="SearchInput" name="SearchInput" type="text" aria-label="Search Input" />
<a href="#" onclick="location.href='/search?term=' + encodeURIComponent(document.getElementById('SearchInput').value); return false;">SEARCH</a>
In this code, we use the encodeURIComponent
function to encode the value of SearchInput
so that it can be safely included as a parameter in the URL. We also use location.href
instead of this.href
to set the URL directly instead of modifying the anchor element’s href
attribute. Finally, we return false
at the end of the onclick function to prevent the default behavior of the anchor element, which is to follow the link.