Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change href using javascript function?

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?
      }
    }
  }
like image 222
Dhenhice Avatar asked May 23 '26 20:05

Dhenhice


1 Answers

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]}`
like image 161
scartag Avatar answered May 25 '26 10:05

scartag



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!