Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Adding an input value as a parameter to a hyperlink in HTML

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

 <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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading