Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript - Insert spaces after numbers in textboxes

I'm looking for a way to insert a space after 4 numbers within a textbox.

Example: XXXX XXXX XXXX

I've been able to get the spacing with no arrow keys or arrow keys with no spacing.

I have looked into this question and a few others on the site but I've been unable to solve the issue of the backspace and arrow keys.

Here is my code:

function isNumber(event) {
    event = (event) ? event : window.event;
    var charCode = (event.which) ? event.which : event.keyCode;
    if (charCode > 31 && (charCode < 48 || charCode > 57)) {
        return false;
    }
return true;
}

And here is a JSFiddle for it. This example is very close but I haven't quite got the spacing correct.

Is this possible to do with my current function or do I need to approach this in a different manner?

EDIT: Is it possible to add arrow key functionality without the cursor allows returning to the back after being released?

like image 329
user94614 Avatar asked Feb 07 '23 09:02

user94614


1 Answers

Demo

Problem is You have used keypress events.

 <input type="text" id="test" maxlength="14" name="test" 
     onkeyup="return isNumber(event)" /> 

Same function from the answer you referred

  function isNumber(e) {
   e.target.value = e.target.value.replace(/[^\dA-Z]/g, '').
                      replace(/(.{4})/g, '$1 ').trim();
 }

This Article will clearly explain why keyup and keydown event works but not keypress

To allow arrow keys Demo

You have to use keydown event

like image 199
Gibbs Avatar answered Feb 11 '23 01:02

Gibbs