Search code examples
javascripthtmlhref

Button to pass text from a text box into href call in jsp


I'm trying to allow a user to click a button which then takes the value inside a textbox and adds it to the end of an href call. I currently have a function that adds the two strings together and calls the href but when the button is clicked, nothing seems to happen. Here's what I got so far:

   <!DOCTYPE html>
<html>
  <head>
    <script>

function findAccountID() {
  var text = document.getElementById('textInput');
  var value = encodeURIComponent(text.value); //encode special characters
  location.href = '**href path here**'+value; //goto URL
}

</script>
  </head>
  <body>
    <div>
      <input type="text" id="textInput" />
      <input type="button" value="Find Account ID" onclick="findAccountID();" />
    </div>
  </body>
</html>

Solution

  • You may need to add slash / between location.href & value In the following snippet the newHref variable is concatenation of location.href & textbox value. If you intend to navigate to new url set location.href to this newHref

    function findAccountID() {
      var text = document.getElementById('textInput');
      var value = encodeURIComponent(text.value); //encode special characters
      let newHref = location.href + '/' + value
      console.log(newHref)
    }
    <div>
      <input type="text" id="textInput" />
      <input type="button" value="Find Account ID" onclick="findAccountID();" />
    </div>