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 ?
Using plain-JavaScript, I'd suggest: function space(el, after) { // defaults to a space after 4 characters: after = after || 4; /* removes all characters in the value that aren't a number, or in the range from A to Z (uppercase): */ var v = el. value.
To add space between numbers with JavaScript, we use the number toLocaleString method. const num = 1234567890; const result = num. toLocaleString("fr"); to call num.
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/
I see that you are using Stripe. They offer a nice plugin that will do exactly what you are looking for. Note that you can use this plugin without using Stripe:
https://github.com/stripe/jquery.payment
And if you are looking for a pure javascript and light version, I created one that will support the American Express format (15 digits) as well as Visa, MasterCard and others (16 digits):
https://stackoverflow.com/a/39804917/1895428
Watch out for the simple solutions that will replace the whole value and always put the focus at the end of the input: it can be annoying if the user edits what he previously entered.
Vue input mask
Placeholder Format
For more information: Click here
// Use as plugin
Vue.use(VueMask.VueMaskPlugin);
new Vue({
el: '#app',
data: {
mask_time: '##:##',
mask_price:'###,###,###',
mask_4s:'#### #### #### ####',
placeholder_time: '23:45',
placeholder_4s:'1234 1234 1234 1234',
placeholder_price: '123,123,123',
time: '',
fourspace: '',
price:'',
}
})
.main{
display: flex;
flex-direction: column;
}
<div id="app">
<div class="main">
Type time here:
<input type="text" v-mask="mask_time" v-model="time" :placeholder="placeholder_time">
Type 4 Space here:
<input type="text" v-mask="mask_4s" v-model="fourspace" :placeholder="placeholder_4s">
Enter price here:
<input type="text" v-mask="mask_price" v-model="price" :placeholder="placeholder_price">
</div>
</div>
<script type="text/javascript" src="https://unpkg.com/vue"></script>
<script type="text/javascript" src="https://cdn.jsdelivr.net/npm/v-mask/dist/v-mask.min.js"></script>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With