insert js variable into html href tag

erayner

Essentially, trying to pass different (string) values to a variable

if (result == "A")
        finalLink.push("https://pool.wikitolearn.org/images/pool/d/d0/Not-giant-enough-letter-a.jpg");
if (result == "B")
        finalLink.push("https://img.clipartfest.com/a354883c247102b05c1657698b7bc8ed_-letters-b-23-b-boyjpg-the-letter-b-clipart_205-257.jpeg");
if (result == "C")
        finalLink.push("http://dailydropcap.com/images/C-9.jpg");

and then send the variable to html href tag

<a id="button" href="finalLink">Click me to be redirected to your answer</a>

don't know much javascript but in PHP you can do this by adding {{variableHere}}

connexo

Javascript operates differently. When you do something like you suggested you're still on the server and generating the HTML that will be sent to the browser.

When you try the same with Javascript the HTML is already delivered and must be manipulated at run-time.

For that to work you need to select the element you want to modify (in this case easy by using document.getElementById() because your link actually has an id), then use the DOM API method DOMelement.setAttribute(attributename, value).

var finalLink, result;
var button = document.getElementById("button");

// example: result = "A"
result = "A";

function adjustLink() {
  switch(result) {
      case "A": 
        finalLink = "https://pool.wikitolearn.org/images/pool/d/d0/Not-giant-enough-letter-a.jpg"; 
        break;
      case "B":
        finalLink = "https://img.clipartfest.com/a354883c247102b05c1657698b7bc8ed_-letters-b-23-b-boyjpg-the-letter-b-clipart_205-257.jpeg"; 
        break;
      case "C":
        finalLink = "http://dailydropcap.com/images/C-9.jpg"
        break;
      default:
  }
  button.setAttribute("href", finalLink);
}
<a id="button" onclick="console.log(this.getAttribute('href')); return false;">Link</a>
<!-- return false; makes sure the link target is not followed (use only for this demo code) -->
<button onclick="result = 'A'; adjustLink();">Set result = "A"</button>
<button onclick="result = 'B'; adjustLink();">Set result = "B"</button>
<button onclick="result = 'C', adjustLink();">Set result = "C"</button>

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related