【问题标题】:How to take input from text box and make it a clickable "href tel" next to the text box?如何从文本框中获取输入并使其成为文本框旁边的可点击“href tel”?
【发布时间】:2022-02-22 21:06:11
【问题描述】:

我在网站上有一个显示电话号码的文本框。我想在显示“点击通话”的文本框旁边(或下方,没关系)有一个链接。我希望该链接可以呼叫文本框中显示的任何电话号码,但我不知道如何将该号码实际输入到 tel: 元素中。我可以只取文本框的名称并将其作为“电话:”吗?

这是文本框:

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

我可以这样做吗:

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

或者这是不可能的,还是我必须将输入类型更改为“tel:”?

我提前道歉,因为我对 html 的了解非常有限。

【问题讨论】:

  • 这能回答你的问题吗? Click to call html
  • 不完全。我需要能够从文本框中输入“tel:”,并且该线程并没有真正解决这个问题。

标签: javascript html href tel


【解决方案1】:

在下面的解决方案中,只要&lt;input&gt; 元素有数据输入,phoneValue 变量的值就会更新。当&lt;a&gt; 元素的点击事件触发时,&lt;a&gt; 元素的href 属性被分配在&lt;input&gt; 元素中输入的电话号码。填写isValid()方法验证电话号码。

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>

【讨论】:

    【解决方案2】:

    您可以有一个 JS 函数,当用户单击 Click to call 链接时运行该函数,该函数将获取数字输入并将其设置为 href。波纹管可以扩展为包括验证等。

      
      <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>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-03-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-12-09
      相关资源
      最近更新 更多