Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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]}`
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading