Home > Enterprise >  I'm using Javascript for automatically adding hyphens to phone number. Need to modify this to a
I'm using Javascript for automatically adding hyphens to phone number. Need to modify this to a

Time:03-17

I found a very useful bit of JS from another thread for automatically hyphenating numbers, but a by-product of that is that now they've entered 10 numbers (US phone number) but if they want to delete and change it, they will have to delete the hyphens as well. I realize this is not a huge deal but it's annoying me and I wanted to find a better solution.

A couple of different options come to mind, just not sure what is possible:

  1. Add/modify my code so that as they delete, it automatically removes the hyphens as they delete their numbers, so they are only pressing backspace 10 times instead of 12.

  2. Have the appearance of hyphens in the text box but they are not actually in the text input area...just like a "background image" so to speak. I tried to do this with a background SVG for the text area but I was not able to solve the problem of automatically spacing out the phone number around the fake hyphens. As for this possible solution, I am fine with these being there all the time even before anything is typed, or appearing once they begin typing the number.

I have searched extensively but have not found anything for what I need. I am sure that a thread already exists but I just haven't searched for the right terms. if anyone has a link to one, even that would be amazing.

Here is my existing code...hopefully this is something I can accomplish with adding something simple. Any help is greatly appreciated.

$('#phone').keyup(function(){
    $(this).val($(this).val().replace(/(\d{3})\-?(\d{3})\-?(\d{4})/,'$1-$2-$3'))
});

CodePudding user response:

Since the number is only formatted when a minimum of ten numbers are entered, you can try something like this.

$('#phone').keyup(function(){
    if( $(this).val().length < 10 ){
        $(this).val($(this).val().replace(/-/g, ''))
    }else{
        $(this).val($(this).val().replace(/(\d{3})\-?(\d{3})\-?(\d{4})/,'$1-$2-$3'))
    }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" id="phone">

  • Related