1

I'm wanting to input a phone number into a form element, and generate a clickable TEL: link. When a user inputs a number, it should display a clickable link with that number in the paragraph below. Example, if you enter 800-888-8888 it would generate html code: <a href="tel:800-888-8888">800-888-8888</a>

<form>
  <label>Phone Number</label><br>
  <input type="text" id="phone" >
</form>
<p id="telLink">This text will be replaced by the link</p>
1
  • 2
    Seems like you forgot to add the JavaScript code you're having issues with... And PS, you don't need <form> if all you need is to plain-generate a HTML output - which on itself seems like half of your task. Commented Jan 29, 2021 at 22:57

2 Answers 2

2

You can set an event listener on the input, and change the innerHTML of #telLink accordingly:

const telLink = document.getElementById("telLink");
const phoneInput = document.getElementById("phone");

phoneInput.addEventListener("input", e => {
  const phone = e.currentTarget.value;
  const link = phone ? `<a href="tel:${phone}">${phone}</a>` : '';
  telLink.innerHTML = link;
});
<form>
  <label>Phone Number</label><br>
  <input type="text" id="phone" >
</form>
<p id="telLink"></p>

Sign up to request clarification or add additional context in comments.

1 Comment

Even if Event.target is correct in this specific case - Event.currentTarget should be used - just for muscle memory. Use Event.target in those rare cases and when you really, really know what you're doing.
1
<form>
  <label>Phone Number</label><br>
  <input type="text" id="phone" onchange="generateLink(this.value)">
</form>
<p id="telLink">This text will be replaced by the link</p>

<script>
   function generateLink(number) {
      if (number.length) {
         document.getElementById('telLink').innerHTML = `<a href="tel:${number}">${number}</a>`
      } else {
         document.getElementById('telLink').innerHTML = 'This text will be replaced by the link'
      }
   }
</script>

**Edited to correct the closing a tag

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.