Search code examples
javascriptanchorhref

Append input string to anchor tag href


Trying to append a string inputted by a user to an anchor tag href using vanilla js.

<script>
    function searchProduct(){
    var inputId = document.getElementById('inputId').value;
    document.getElementById('go').href = "mywebsite/product/" + inputId;
}
    searchProduct();
</script>


<a id="go"><p>Go</p></a>

However, this is not functioning


Solution

  • You're triggering searchProduct() once, when the page is loaded. You need to trigger this after the input with the ID inputId is updated -- whether through a button press or when they leave the textbox, or something.

    Here is an example which triggers the searchProduct() function when they leave the textbox:

    (function() {
      function searchProduct(){
        var inputId = document.getElementById('inputId').value;
        document.getElementById('go').href = "mywebsite/product/" + inputId;
      }
    
      document.getElementById('inputId').addEventListener('blur', function() {
        searchProduct()
      });
    })();
    

    See this jsBin