Ryan
Ryan

Reputation: 29

Attach a function after clicking outside the input with javascript and html

My html is:

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

Here is my 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 = "";
}
}

what i want is to check the format of the phone after the user click outside the input field?

Upvotes: 0

Views: 1830

Answers (3)

Aleksandar
Aleksandar

Reputation: 460

Is this what you are looking for?

    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 = "";
    }
    })
<input class="UserInfo" type="text" placeholder="phone Format" id="Phone_num">

Upvotes: 2

Sachin Yadav
Sachin Yadav

Reputation: 806

document.getElementById("Phone_num").value

AND

document.getElementById("phone_num").value

There is a typo, Attribute values are always case-sensitive. The id value should either be Phone_num or phone_num

Upvotes: 3

Calvin Bonner
Calvin Bonner

Reputation: 580

I believe what you are looking for is

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

You can read more about it here W3 Schools onFocusOut

Upvotes: 2

Related Questions