Paul Herrmann
Paul Herrmann

Reputation: 21

Changing a target link with javascript

I am trying to build a simple "form" where you input a "from" address and a "to" address and hit "OK".

I want the script to take the "from" and "to" and a preset text "maps.google.com/dir/ from / to" and change the a href value to that link.

Here is what I got from similar tutorials:

    <script type="text/javascript">
function getlinks(){
    var from = document.getElementById('from').value;
    var to = document.getElementById('to').value;
    var lnkgm = document.getElementById('lnkgm');
    lnkgm.href = "https://www.google.de/maps/dir/" + from + "/" + to;
}
</script>
From: <input type='text' id='from' value='' /><br>
To: <input type='text' id='to' value='' /><br>
<input type='button' onclick='getlinks()' value='OK'/><p>
<a href="lnkgm"><img src="image.png"></a>

this kinda worked in a text version using a "innerHTML" but I want the script to update the

Any pointers?

Thank you so much!

Upvotes: 0

Views: 81

Answers (2)

user6269864
user6269864

Reputation:

You forgot to add the ID to your link:

<a id="lnkgm" href="lnkgm"><img src="image.png"></a>

Upvotes: 0

DontVoteMeDown
DontVoteMeDown

Reputation: 21465

Just change the href attribute to id:

<a href="lnkgm">

To

<a id="lnkgm" href="#">

As you're trying to get the element by id (document.getElementById('lnkgm')) you have to set it's id attribute.

Demo:

function getlinks(){
    var from = document.getElementById('from').value;
    var to = document.getElementById('to').value;
    var lnkgm = document.getElementById('lnkgm');
    lnkgm.href = "https://www.google.de/maps/dir/" + from + "/" + to;
  console.log(lnkgm.href);
}
From: <input type='text' id='from' value='' /><br>
To: <input type='text' id='to' value='' /><br>
<input type='button' onclick='getlinks()' value='OK'/><p>
<a id="lnkgm" href="#"><img src="image.png"></a>

Upvotes: 1

Related Questions