最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

html - Plain Javascript way to add a space on the fly after every 5th digit in input field - Stack Overflow

programmeradmin2浏览0评论

How can I add a space after every 5th number (as the user types) in input field?

12345 56789 12345 56789

The limitation is that I cannot use any framework like jQuery. This has to be done using plain Javascript or CSS.

I also need to support the ability to hit backspace and correct the number or place cursor anywhere and start correcting with backspace.

The following code is based on the answer here: How to insert space every 4 characters for IBAN registering?

The backspace does not work reliably.

function space(str, after) {
  if (!str) {
    return false;
  }
  after = after || 4;
  var v = str.replace(/[^\dA-Z]/g, ''),
    reg = new RegExp(".{" + after + "}", "g");
  return v.replace(reg, function(a) {
    return a + ' ';
  });
}

var el = document.getElementById('pin');
el.addEventListener('keyup', function() {
  this.value = space(this.value, 4);
});
<form>
  <input autocapitalize="off" autocorrect="off" maxlength=20 type="text" placeholder="type the pin" id="pin" name="pin" />
  <script>
  </script>
</form>

How can I add a space after every 5th number (as the user types) in input field?

12345 56789 12345 56789

The limitation is that I cannot use any framework like jQuery. This has to be done using plain Javascript or CSS.

I also need to support the ability to hit backspace and correct the number or place cursor anywhere and start correcting with backspace.

The following code is based on the answer here: How to insert space every 4 characters for IBAN registering?

The backspace does not work reliably.

function space(str, after) {
  if (!str) {
    return false;
  }
  after = after || 4;
  var v = str.replace(/[^\dA-Z]/g, ''),
    reg = new RegExp(".{" + after + "}", "g");
  return v.replace(reg, function(a) {
    return a + ' ';
  });
}

var el = document.getElementById('pin');
el.addEventListener('keyup', function() {
  this.value = space(this.value, 4);
});
<form>
  <input autocapitalize="off" autocorrect="off" maxlength=20 type="text" placeholder="type the pin" id="pin" name="pin" />
  <script>
  </script>
</form>

Share Improve this question edited May 23, 2017 at 12:34 CommunityBot 11 silver badge asked Mar 28, 2015 at 1:43 akirekaduakirekadu 2,3573 gold badges24 silver badges31 bronze badges 5
  • Keep count of letter after every key stroke – coder hacker Commented Mar 28, 2015 at 1:45
  • 1 If a user enters 1234567890 and it auto spaces to 12345 67890 and the user goes back and edits the number by adding another 6 at the end of the first grouping should it correct to 12345 6 67890 or 12345 66789 0? – bdrx Commented Mar 28, 2015 at 2:57
  • @brdx, if a group is full, adding another digit shouldn't be allowed. I'm thinking this would be the most intuitive (or least confusing) behavior from end user point of view. – akirekadu Commented Mar 28, 2015 at 5:13
  • 1 It sounds like having multiple input boxes each with a 5 digit only validation is more what you want. After all the fields are entered you can just bine them into one string – bdrx Commented Mar 28, 2015 at 15:51
  • @brdx, The solution you are suggesting is definitely more flexible and reliable than manipulating text in one input field. I'll write this version and test it out. – akirekadu Commented Mar 29, 2015 at 23:39
Add a ment  | 

2 Answers 2

Reset to default 10

Here is a relatively short approach:

Just add an event listener for the input event (or keyup/keydown), and then use some regex.

In the example directly below, all whitespace is initially removed using .replace(/\s/g, ''), and then .replace(/(\d{5})/g, '$1 ') essentially adds a space after every 5th character.

The reason all the whitespace is removed is so that there is always a space between every 5th character (even if you go back and edit previous characters).

document.getElementById('target').addEventListener('input', function (e) {
  e.target.value = e.target.value.replace(/\s/g, '').replace(/(\d{5})/g, '$1 ').trim();
});
<input id="target" type="text"/>


It seems like the only caveat with the approach above is that the caret's position is lost when editing previous characters.

If you want to prevent this, retrieve the caret's current position by accessing the selectionEnd property and then set the caret's position after the regex formatting has been applied.

document.getElementById('target').addEventListener('input', function (e) {
  var target = e.target, position = target.selectionEnd, length = target.value.length;
  
  target.value = target.value.replace(/\s/g, '').replace(/(\d{5})/g, '$1 ').trim();
  target.selectionEnd = position += ((target.value.charAt(position - 1) === ' ' && target.value.charAt(length - 1) === ' ' && length !== target.value.length) ? 1 : 0);
});
<input id="target" type="text"/>

You will notice that there is a slight issue when the character after the caret is a space (because the space wasn't accounted for when initially retrieving the caret's position to begin with). To fix this, the position is manually incremented if the succeeding character is a space (assuming a space was actually added - which is determined by paring the length before and after replacing the characters).

function myFunction() {
    str = document.getElementById('num').value;

    str=str.replace(/\s/g, '');
    if(str.length%5==0){
    
        document.getElementById('num').value+=" ";
    }
}
<input id='num' type="text" onkeyup="myFunction()">

发布评论

评论列表(0)

  1. 暂无评论