0

I am trying to append - between phone numbers in user input to be like xxx-xxx-xxxx instead of xxxxxxxxxx .

This is working fine when using Keys to enter value but what about Pasting the number or Chrome Auto-fill function? For example if you copy and paste 2222222222 to the input the - will not added between.

How can I fix this?

 $(function () {

            $('#txtnumber').keydown(function (e) {
             var key = e.charCode || e.keyCode || 0;
             $text = $(this); 
             if (key !== 8 && key !== 9) {
                 if ($text.val().length === 3) {
                     $text.val($text.val() + '-');
                 }
                 if ($text.val().length === 7) {
                     $text.val($text.val() + '-');
                 }
             }

             return (key == 8 || key == 9 || key == 46 || (key >= 48 && key <= 57) || (key >= 96 && key <= 105));
         })
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
 <input id="txtnumber"   type="text" maxlength="12" placeholder="xxx-xxx-xxxx" /><br /><br />
halfer
  • 19,824
  • 17
  • 99
  • 186
Mona Coder
  • 6,212
  • 18
  • 66
  • 128

1 Answers1

0

you need to capture the Ctrl key + V, and then insert your -'s

var ctrlDown = false,
    ctrlKey = 17,
    cmdKey = 91,
    vKey = 86,
    cKey = 67;

$(document).keydown(function(e) {
    if (e.keyCode == ctrlKey || e.keyCode == cmdKey) ctrlDown = true;
}).keyup(function(e) {
    if (e.keyCode == ctrlKey || e.keyCode == cmdKey) ctrlDown = false;
});

/// your code + 
$(function () {

        $('#txtnumber').keydown(function (e) {
         var key = e.charCode || e.keyCode || 0;
         if (ctrlDown && (e.keyCode == vKey)){
                //insert the -'s on respective possition
         }
         else{
          $text = $(this); 
          if (key !== 8 && key !== 9) {
             if ($text.val().length === 3) {
                 $text.val($text.val() + '-');
             }
             if ($text.val().length === 7) {
                 $text.val($text.val() + '-');
             }
         }
         }

credits to> https://stackoverflow.com/a/2904944/335905

celerno
  • 1,367
  • 11
  • 30