Making a href variable that changes with text input

Viewed 35

I'm trying to make a mailto: link change based on a text input and a button.

I managed to make it work without a href, with just plain text from a paragraph, but i can't manage to make it work on the href.

I get either [object HTMLInputElement] or undefined

HTML

    <input type="text" id="email_input"><br>
    <span id="links"><a id="email">email</a></span><br>


    <input type="button" id="btn" value="Submit"><br>

JAVASCRIPT

var emailIN = document.getElementById('email_input');
var emailOUT = document.getElementById('email');
var emailLink = "mailto:"+emailOUT;



btn.onclick = function(){
    /* addressOUT.textContent = addressIN.value; */
   /*  emailOUT.setAttribute("href",emailIN); */
    /* emailOUT.textContent = "mailto:"+emailIN.value; */
    /* $("a#email").attr('href','mailto:'+emailIN); */
    /* document.querySelector("#email").href=emailLink; */
   
   document.getElementById("email").value = "mailto:"+emailIN
     emailOUT.href = "mailto:"+emailIN;
}
1 Answers

Here is an example.

document.getElementById('btn').addEventListener('click', function() {
  const emailInput = document.getElementById('email_input');
  const emailLink = document.getElementById('email');
  const href = emailInput.value != '' ? 'mailto:' + emailInput.value : '';
  if (href.length > 0) {
    emailLink.setAttribute('href', href);
    console.log(`Link href is change to ${href}`);
  }
});
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8" />
  <meta http-equiv="X-UA-Compatible" content="IE=edge" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" />
</head>

<body>
  <div class="container">
    <div class="my-5">
      <div class="mb-3">
        <label for="email_input" class="form-label">Email address</label>
        <input class="form-control" id="email_input" placeholder="name@example.com" />
      </div>
      <div class="mb-3">
        <a id="email" href="">Email Link</a>
      </div>
      <div class="mb-3">
        <button type="button" id="btn" class="btn btn-primary btn-md">Submit</button>
      </div>
    </div>
  </div>
</body>

</html>

Related