skip to Main Content

I wish this to redirect an inputted port to redirect to same url with port,

Someone helped me this far but still have no luck…

<script>
document.getElementById('myForm').addEventListener('submit', function(event) {
    event.preventDefault(); 

    // Get the value from the input field
    const port = document.getElementById('portNumber').value;
    const baseUrl = "h--ps://mysite.com";
    window.location.href = '${baseUrl}:${port}';
    
});
</script>



<form id="myForm" method="post" action="javascript:void(0)">
    <input type="number" name="" id="myForm" placeholder="Port Number.." />
    <input type="submit" value="Go"/>
</form>

2

Answers


  1. window.location.href = `${baseUrl}:${port}`;
    

    use ` instead of ‘

    <input type="number" name="" id="portNumber" placeholder="Port Number.." />
    

    You forgot to change id="portNumber" in input.

    Login or Signup to reply.
  2. You are not very far from target but you have some small mistakes.

    • myForm should not be used more than one element.
    • Template literals work with backtick not with single quote.
    • id of your input must be portNumber

    Before trying below example make sure that given address will throw an error because of "h--ps://mysite.com".

    document.getElementById('myForm').addEventListener('submit', function(event) {
      event.preventDefault();
      // Get the value from the input field
      const port = document.getElementById('portNumber').value;
      const baseUrl = "h--ps://mysite.com";
      console.log(`${baseUrl}:${port}`);
      window.location.href = `${baseUrl}:${port}`;
    });
      <form id="myForm" method="post" action="javascript:void(0)">
        <input type="number" id="portNumber" name="" placeholder="Port Number.." />
        <input type="submit" value="Go"/>
      </form>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search