shane Johnson
shane Johnson

Reputation: 69

Generate link from form field Javascript

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>

Upvotes: 1

Views: 67

Answers (2)

Dejan Sandic
Dejan Sandic

Reputation: 451

<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

Upvotes: 1

Majed Badawi
Majed Badawi

Reputation: 28414

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>

Upvotes: 2

Related Questions