Search code examples
javascriptjquerymailto

Use javascript to replace input value into mailto


I have to email some information and I can't use PHP unfortunately. I've set up an input to get the email address of a user.

<form name="email-form">
    <div class="email">
        Enter your email:
        <input type="email" name="email-value">
    </div>
    <a type="submit" class="email-link" value="Email Results"></a>
</form>

What I thought I could do is set up an onClick event like this and append the user input to the end of the mailto: part.

var emailAddy = $("email-value").val();
    $(".email-link").on("click", function(){
        $(".email-link").prop("href", "mailto:").append( emailAddy );

    });

In don't get any errors running this code, but when the mail client comes up, the "to:" section is blank. Is this even possible?


Solution

  • There's a lot going on here.

    • $("email-value") doesn't match anything. You want $('input[name="email-value"]').
    • You're trying to capture the email address in a global variable on page load, before the user has an opportunity to enter anything, so it'll always be empty. Instead, you should capture that value inside the function that uses it.
    • .append adds a text node to the document. What you want is to concatenate the email address to the string "mailto:", so just use concatenation (+).
    • <a> tags don't have a value attribute. Use a text node inside the tag instead.
    • <a> tags don't have a type attribute, and aren't a submit button for a form. Fortunately, what you're doing is constructing a regular anchor link, so it doesn't need to be a submit button; the only use for the form is for the input field.
    • There's no href attribute on the anchor to begin with, so the browser won't style it as a link.
    • href is an attribute, not a prop: use .attr(). prop is for booleans such as checked or disabled.
    • You're altering the link's href during the same click event that would fire that link. That does seem to work -- somewhat unexpectedly -- but means the hover indicator on the link will be incorrect (since the href doesn't exist until the user clicks the link.) I'd use a change event on the input field instead (and ideally validate the email address before altering the link href.)

    Here's a corrected version of your code:

    $('input[name="email-value"]').on("change", function() {
      var emailAddress = $(this).val();
      // validate the address here
      $(".email-link").attr("href", "mailto:" + emailAddress);
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <form name="email-form">
      <div class="email">
        Enter your email:
        <input type="email" name="email-value">
      </div>
    </form>
    <a href="#" class="email-link">Email Results</a>