Siesta Siesta - 2 months ago 9
HTML Question

Javascript variable into href="mailto:" string

I am trying to create a simple page that can take some user inputs and print them back out, and I have found a way that is working fine. But there is one thing I can not manage to do, and that is to take the E-post input from the user and add it into the "mailto" string so that when the entered mail is clicked it will open in the users e-mail program with the entered mail preentered.

Here is the code

<!DOCTYPE html>
<html>
<head>
<title>HTML JavaScript output on same page</title>
<script type="text/JavaScript">
function showMessage(){
var navn = document.getElementById("navn").value;
display_navn.innerHTML= navn;

var mail = document.getElementById("mail").value;
display_mail.innerHTML= mail;

var tlf = document.getElementById("tlf").value;
display_tlf.innerHTML= tlf;
}
</script>
</head>
<body>
<form>
Navn: <br>
<input type="text" id = "navn"><br>
E-post: <br>
<input type="text" id = "mail"><br>
Mobil: <br>
<input type="text" id = "tlf"><br>

<br>
<br>
<input type="button" onclick="showMessage()" value="submit" />
</form>

<br>
<br>

<span id = "display_navn"></span><br>
<br>
<a href="mailto:" + mail><span id = "display_mail"></a></span><br>
<br>
<span id = "display_tlf"></span>


</body>
</html>


And here is a screenshot of what it looks like.

enter image description here

And I want to make it so that when I click on TestEmail the e-mail client I have opens, and the adress is entered already. Is this something that can be done?
If it would be hard to do it on the same site, I could consider having the inputs on a single site, and then open a new site with the generated content when clicking on the submit button if that would be easyer.

Answer

You just need this extra line of code:

display_mail.parentNode.setAttribute("href", "mailto:" + mail);

And don't forget to close the </form> tag.

Fiddle: http://output.jsbin.com/revahabowe

Comments