2

I found this tutorial from here.It would appear like this:35-354-55444-54-54324..It works fine but when i try to edit any code it is not working correctly.when i press backspace it takes automatically number.Here is my code:

function format(input, format, sep) {
  var output = "";
  var idx = 0;
  for (var i = 0; i < format.length && idx < input.length; i++) {
    output += input.substr(idx, format[i]);
    if (idx + format[i] < input.length) output += sep;
    idx += format[i];
  }

  output += input.substr(idx);
  return output;
}

$('.creditCardText').keyup(function() {
  var foo = $(this).val().replace(/-/g, ""); // remove hyphens
  // You may want to remove all non-digits here
  // var foo = $(this).val().replace(/\D/g, "");

  if (foo.length > 0) {
    foo = format(foo, [2, 3, 5, 2, 5], "-");
  }

  $(this).val(foo);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<input class="creditCardText" maxlength="21" />
VLAZ
  • 26,331
  • 9
  • 49
  • 67
Anondi
  • 76
  • 8
  • Please be clear about the problem you're facing. What is not working? Can you give an example? – 31piy Aug 14 '18 at 04:57
  • This code is fully working but when i'm trying to edit any number its not working correctly.Suppose i have a number like '75-354-55444-54-54324' now i want to remove 7 using backspace and add 2 on the place of 7.This is not working here. – Anondi Aug 14 '18 at 05:02

1 Answers1

1

The actual problem is, as I understand it, the string gets reformatted when you delete a number somewhere, plus the cursor jumps to the end. This makes it hard to do quick and meaningful edits.

I suggest to trap the backspace and delete keys and skip the string reformatting process in that case. This can have side effects but should suit your needs.

function format(input, format, sep) {
  var output = "";
  var idx = 0;
  for (var i = 0; i < format.length && idx < input.length; i++) {
    output += input.substr(idx, format[i]);
    if (idx + format[i] < input.length) output += sep;
    idx += format[i];
  }

  output += input.substr(idx);
  return output;
}

$('.customerNumberText').keyup(function(e) {
  if(e.keyCode == 8   //alert('backspace')
  || e.keyCode == 46) //alert('delete')
  return;


  var foo = $(this).val().replace(/-/g, ""); // remove hyphens
  // You may want to remove all non-digits here
  // var foo = $(this).val().replace(/\D/g, "");

  if (foo.length > 0) {
    foo = format(foo, [2, 3, 5, 2, 5], "-");
  }

  $(this).val(foo);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<input class="customerNumberText" maxlength="21" />
wp78de
  • 18,207
  • 7
  • 43
  • 71