Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
748 views
in Technique[技术] by (71.8m points)

javascript - How to insert space after four characters in html input?

I need to insert a space after every four characters while the user is typing a credit card number using JavaScript .

<input type="text" size="19" maxlength="19" data-stripe="number" placeholder="1234 5678 9012 3456">

What is the best way to accomplish this ?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

try this:

input:

<input type="text" maxlength="19" class="text" />

jquery:

$('.text').on('keyup', function() {
  var foo = $(this).val().split(" ").join(""); 
  if (foo.length > 0) {
    foo = foo.match(new RegExp('.{1,4}', 'g')).join(" ");
  }
  $(this).val(foo);
});

fiddle: https://jsfiddle.net/juspC/126/


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...