【问题标题】:Attach a function after clicking outside the input with javascript and html用javascript和html在输入外点击后附加一个函数
【发布时间】:2020-12-01 19:03:06
【问题描述】:

我的html是:

<input class="UserInfo" type="text" placeholder="phone Format" id="Phone_num">

这是我的 js:

function checkPhoneFormat(){
const phone = document.getElementById("Phone_num").value;
const phoneFormatRex = /^\+?[0-9(),.-]+$/;
var match = phoneFormatRex.exec(phone);
if (match) {
    document.getElementById("Phone_num").value = phone;
}
else {
    document.getElementById("Phone_num").value = "";
}
}

我想要的是在用户点击输入字段外后检查手机的格式?

【问题讨论】:

    标签: javascript html


    【解决方案1】:
    document.getElementById("Phone_num").value
    

    document.getElementById("phone_num").value
    

    有一个错字,属性值总是区分大小写的。 id 值应为Phone_numphone_num

    【讨论】:

    【解决方案2】:

    这是你要找的吗?

        var input = document.getElementById("Phone_num");
        input.addEventListener("blur", function(){
            const phone = document.getElementById("Phone_num").value;
        const phoneFormatRex = /^\+?[0-9(),.-]+$/;
        var match = phoneFormatRex.exec(phone);
        if (match) {
            document.getElementById("Phone_num").value = phone;
        }
        else {
            document.getElementById("Phone_num").value = "";
        }
        })
    &lt;input class="UserInfo" type="text" placeholder="phone Format" id="Phone_num"&gt;

    【讨论】:

      【解决方案3】:

      我相信你正在寻找的是

      <input type="text" onfocusout="myFunction()">
      

      您可以在此处阅读更多信息W3 Schools onFocusOut

      【讨论】:

      • 我想这只会关注输入字段而不是检查它的类型
      • 对不起,我想我应该澄清一下。将onfocusout 与您的函数一起使用将导致它在失去焦点时运行checkPhoneFormat() 函数(例如,当用户单击输入或选项卡到下一个输入时)。onfocusout 不会使输入成为焦点。
      • 是的,我已经尝试过了,它不会检查输入中值的格式。那么我该怎么做才能检查输入值的格式
      猜你喜欢
      • 2011-12-23
      • 1970-01-01
      • 1970-01-01
      • 2016-04-22
      • 2017-11-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-06-01
      相关资源
      最近更新 更多