How to change href using javascript function?

Advertisements

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?
      }
    }
  }

>Solution :

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]}`

Leave a ReplyCancel reply