Javascript - Inserting spaces after numbers in text windows

I am looking for a way to insert a space after 4 numbers in a text box.

Example: XXXX XXXX XXXX

I managed to get an interval without arrow keys or arrow keys without interval.

I looked at this question and several others on the site, but I was not able to solve the problem with reverse space 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 the JSFiddle . This example is very close, but I did not quite understand the interval.

Is it possible to do this with my current function, or do I need to approach this differently?

EDIT : Is it possible to add the functionality of the arrow keys if the cursor does not allow to return to the background after releasing?

+4
4

: .

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

,

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

, keyup keydown, keypress

keydown

+8

, oninput-, .

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

JS:

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

, , , .

, , .

regex, , , , .

Code using REgex from @Gops AB:

function isNumber(event,el) {
    event = (event) ? event : window.event;

    var charCode = (event.which) ? event.which : event.keyCode;

      if (charCode > 31 && (charCode < 48 || charCode > 57)) {
        return false;
    }
    //Add a space after 4 numbers.


    var v=el.value + String.fromCharCode(charCode); //Keypress does not let us see the value of the text box after the press, so we have to add the string to our comparison.
    v=v.replace(/\s/g,'');

    el.value=v.replace(/(.{4})/g, '$1 ').trim(); // using regex from other answer. Thanks @Gops AB for the example
    return false;
}

Demo using Regex: http://jsfiddle.net/gregborbonus/Lm2hS/3208/

0
source

Here is the most effective way to reduce it:

// HTML

<input type="text" id="cc" name="cc" maxlength="19">

// JS

init=()=>document.getElementById('cc').addEventListener('keyup',(e)=>e.target.value = e.target.value.replace(/[^\dA-Z]/g, '').replace(/(.{4})/g, '$1 ').trim());
document.addEventListener('DOMContentLoaded', init);
0
source

All Articles