1

I have a text box on a website that displays a phone number. I'd like to have a link next to the text box (or underneath, doesn't matter) that says "Click to call". I want that link to call whatever phone number is displayed in the text box, but I can't figure out how to actually get that number into the tel: element. Can I just take the name of the text box and put that as the "tel:"?

Here's the text box:

<input name="txtPhone" type="text" id="txtPhone" onkeydown="javascript:ShowSave();" onchange="javascript:ShowSave();" style="width:120px;">

Can I just do something like this:

<a href="tel:[txtPhone]" >Click to call</a>

Or is that not possible or would I have to change the input type to "tel:"?

I apologize ahead of time as my knowledge of html is extremely limited.

Sercan
  • 4,739
  • 3
  • 17
  • 36
FeeJee
  • 21
  • 2
  • Does this answer your question? [Click to call html](https://stackoverflow.com/questions/26088523/click-to-call-html) – Will Jan 27 '22 at 18:11
  • Not quite. I need to be able to make the "tel:" the input from the text box and that thread doesn't really go over that. – FeeJee Jan 27 '22 at 18:18

2 Answers2

0

In the solution below, the value of the phoneValue variable is updated as long as there is a data input to the <input> element. When the <a> element's click event fires, the <a> element's href attribute is assigned the phone number entered in the <input> element. Fill in the isValid() method to verify the phone number.

let inputElement = document.getElementById('txtPhone');
let phoneLinkElement = document.getElementById('tel');
let phoneValue;

/* User input can be validated within this method. */
function isValid(){
  return true;
}

/* This method fires when data is input to the <input> element. */
inputElement.addEventListener('input', function() {
  phoneValue = this.value;
  console.log(`Current User Input: ${phoneValue}`);
});

/* This event fires when the <a> element is clicked. */
phoneLinkElement.addEventListener('click', function() {  
  if(isValid()){
    phoneLinkElement.href = `tel: ${phoneValue}`;
  }
});
#txtPhone {
  width: 120px;
}
<input name="txtPhone" type="text" id="txtPhone">
<a id="tel" href="">Tel</a>
Sercan
  • 4,739
  • 3
  • 17
  • 36
0

You can have a JS function that runs when the user clicks the Click to call link which will get the number input and set it as href. The bellow can be expanded to include validation and so forth.

  
  <input type="text" placeholder="Telephone" id="telInput">
  <a href="#" id="tel" onclick="changeHref()">Click to call</a>

  <script>
      function changeHref(){
          // Selecting the input element and get its value 
          let inputVal = document.getElementById("telInput").value;
          // Set it for the href
          document.getElementById("tel").setAttribute("href", `tel:${inputVal}`);

          // Test
          console.log(inputVal);
      }
  </script>
Sorin
  • 767
  • 12
  • 17