1
votes

Encountered a problem - I want to include a js-variable in the body of a mail, which users can forward to friends, using the following:

<head>
<script src="javascript.js" type="text/javascript">
</script>

<body>    
<script type="text/javascript">
    document.write('<a href="mailto:?subject=Subject&body=Bodytext' +total+ '">Mail me</a>');</script>
</body>

The var total is defined in the .js file, and it's value can be manipulated by executing af function attached to a form.

Even after the function is carried out and the page displays the changes, the opened mail will always display the default value of var total instead of the manipulated.

Basically my question is: How do I get the modified var total to display inside the mailto-link, instead of the default var total.

Disclaimer: I'm not very smart (when it comes to coding at least).

Bonus-info: I've made it possible to share the var total with Facebook using FB.init etc., which perfectly displays the manipulated var.

Edit:

JS (cut a bit short):

var total = 'empty';

function getCalculation() {
total = (parseInt(f1) + parseInt(f2)).toFixed(0);
document.contactForm.formTotal.value = total;
}
1
copy the according part of "javascript.js" in here, please.Axel Amthor

1 Answers

3
votes

The document.write is only run once when the page is generated. It is not a dynamic code that gets triggered every time something changes. You need a different approach for this.

Instead of the document.write, just make a normal html link (a-element) with javascript as the href where you change the document url to the mailto link.

For example:

<a href="javascript:location.href='mailto:[email protected]?subject=Subject&body=Bodytext' + total">Mail Me</a>

This means that when the link is clicked, instead of going to an URL, we execute a piece of JavaScript that changes the document's location to the mailto-link, and only THEN embeds the value of the total -variable into the body.

Even better way is to create an external function that you trigger when that link is clicked:

<script type="text/javascript">
    function sendMail() {
        var email = '[email protected]';
        var subject = 'My subject';
        var body = 'This is the total: ' + total;
        location.href = 'mailto:' + email
            + '?subject=' + encodeURIComponent(subject)
            + '&body=' + encodeURIComponent(body);
    }
</script>

And then in the link you add the following href:

<a href="javascript:sendMail()">Mail Me</a>

Now the total variable gets embedded in the email body every time the link is clicked, instead of when the page is loaded.

The encodeURIComponent makes sure the subject and body are encoded properly, so that all the special characters and spaces, etc gets translated correctly in the mail client.

I hope that helps!