0

How to re-edit letter from the following textbox

$('.zip-code').on('keypress change', function () {
  $(this).val(function (index, value) {
    return value.replace(/\W/gi, '').replace(/(.{3})/g, '$1 ');
  });
}); 
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label class="label" for="credit-card">zip Code</label>
<input type="text" maxlength="7" class="zip-code" value="" autocomplete="off"  />

The above code gives space after 3 letters but unable to re-edit the letter

following are the issues faced :

  1. should remove entire zip-code to edit a letter in textbox
  2. If the zip-code entered wrong and if needed to edit it , unable to edit the letter/letters in zip-code field.
  3. after editing the zip-code the letter moves to the end.
Shiladitya
  • 12,003
  • 15
  • 25
  • 38
DUMB_CODER
  • 81
  • 1
  • 2
  • 9

1 Answers1

1

Your problem here is a few issues. First, you want to use keyup to get the value otherwise it will fire before the key value is set and not give an accurate value when called. Second, your regex is running while you are potentially still typing which forces the cursor to the end. You can overcome this using a timer (Borrowed from this answer).

Try the snippet below, I believe this accomplishes what you are after.

var typingTimer;                //timer identifier
var doneTypingInterval = 1000;  //time in ms, 1 second for example
var $input = $('.zip-code');

//on keyup, start the countdown
$input.on('keyup', function () {
  clearTimeout(typingTimer);
  typingTimer = setTimeout(formatZip, doneTypingInterval);
}).on('keydown', function () {
  clearTimeout(typingTimer);
});

function formatZip () {
  $input.val(function (index, value) {;
    var str = value.replace(/\W/gi, ''),
        newVal = [str.slice(0, 3), ' ', str.slice(3,6)].join('');
    return newVal;
  });
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label class="label" for="credit-card">zip Code</label>
<input type="text" maxlength="7" class="zip-code" value="" autocomplete="off"  />
Dave Gillem
  • 476
  • 4
  • 10