skip to Main Content

I have a button, that when a user clicks on it, The page will be redirected to another link.

Index.html:

<input
  type="text"
  placeholder="Search"
  id="input-box"
  autocomplete="off"
  style="width: 250px;">
<button id="submitbtn"
        onClick="submitClicked"
        href="">
</button>
</input>

Script.js:

document.getElementById("submitbtn").onclick = function() {submitBtn()};

  function submitBtn() {
    for(let i=0; i<availableKeywords.length; i++){
      if (result == availableKeywords[i]){ //checks if the result(inputted by the user) is matched with the keyword
        document.getElementById("submitbtn").href = "/index2.html?key=${availableKey[i]}" //How do i make this work?
      }
    }
  }

2

Answers


  1. button does not have href property inherently but you can set it as an attribute.

    document.getElementById("submitbtn").setAttribute("href", `/index2.html?key=${availableKey[i]}`);
    

    I probably should point out that this will not automatically redirect though.

    To do a redirect, you can use window.location.href instead.

    Replace your button update code with this.

    window.location.href = `/index2.html?key=${availableKey[i]}`
    
    Login or Signup to reply.
  2. Comments

    1. Html input tags do not have closing tags.
    2. You do not have to set onclick in javascript if you have an onclick in html.

    HTML

    <input id="input-box" type="text" placeholder="Search" autocomplete="off" style="width: 250px;">
    <button id="submit-btn" onclick="submitClicked(this)">Submit</button>
    

    JS

    const availableKeywords = [];
    
    function submitClicked() {
      const input = document.getElementById('input-box');
      const value = input.value ?? null;
    
      for (const keyword of availableKeywords || []) {
        if ( value != keyword ) continue;
        location.href = `${location.origin}/index2.html?key=${keyword}`;
        break;
      }
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search