Generate link from form field Javascript

Tags:



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>

Answer

<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



Source: stackoverflow