M
M
mUchenik2016-09-24 21:39:51
JavaScript
mUchenik, 2016-09-24 21:39:51

How to make a phone number input mask?

Good day, dear experts!
I ask for your advice:
In woocommerce, on the checkout page, in the phone number entry point, I want to implement a mask like: +7(___)-__-__-___ (by default), so that no other characters other than numbers are entered.
But the problem is that I can't figure out which file to edit and what to write.
I found different plugins, but I don’t know how to prescribe them correctly.
I tried this digitalbush.com/projects/masked-input-plugin , nothing worked :(
(though most likely the hands are crooked)
Can someone tell "On the fingers" how to install?
Do not consider it impudent.... I could not figure it out myself .Here
's what I did:
In the header.php file, before I wrote:

<script type="text/javascript" src="zerif-lite/js/jquery-1.7.2.min.js" ></script>
<script type="text/javascript" src="zerif-lite/js/jquery.maskedinput-1.3.min.js"></script>
<script>
$("#billing_phone").mask("(999) 99-99-999");


$("#billing_phone").on("blur", function() {
    var last = $(this).val().substr( $(this).val().indexOf("-") + 1 );
    
    if( last.length == 3 ) {
        var move = $(this).val().substr( $(this).val().indexOf("-") - 1, 1 );
        var lastfour = move + last;
        
        var first = $(this).val().substr( 0, 9 );
        
        $(this).val( first + '-' + lastfour );
    }
});
</script>

If important, then the Zerif Lite template

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Alex Glebov, 2016-09-24
@mUchenik

when the script in the header is executed, the #billing_phone element has not yet been created by the browser, so it does not work.
wrap it up

$(document).ready(function() {
$("#billing_phone").mask("(999) 99-99-999");


$("#billing_phone").on("blur", function() {
    var last = $(this).val().substr( $(this).val().indexOf("-") + 1 );
    
    if( last.length == 3 ) {
        var move = $(this).val().substr( $(this).val().indexOf("-") - 1, 1 );
        var lastfour = move + last;
        
        var first = $(this).val().substr( 0, 9 );
        
        $(this).val( first + '-' + lastfour );
    }
});
}

or move your code to the footer

S
Sergey, 2016-09-25
@void01

or move your code to the footer

or use delegate
api.jquery.com/delegate
although if the element is the only one, judging by the selector, it would be more correct to listen to the previous speaker -))

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question