Hello Guys, for today’s JavaScript tutorial am going to show you how you can automatically include a symbol for Example “-“ in any text input field on an HTML page. This is very important in controlling user inputs in cases like phone numbers, Credit card number and others, the javascript code below is responsible for achieving this simple task.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
jQuery(document).ready(function($){ function format(input, format, sep) { var output = ""; var idx = 0; for (var i = 0; i < format.length && idx < input.length; i++) { output += input.substr(idx, format[i]); if (idx + format[i] < input.length) output += sep; idx += format[i]; } output += input.substr(idx); return output; } $('#Your_Field_Key').keyup(function() { var foo = $(this).val().replace(/-/g, ""); // remove hyphens // You may want to remove all non-digits here // var foo = $(this).val().replace(/\D/g, ""); if (foo.length > 0) { foo = format(foo, [2,2,2,2,2], "-"); } $(this).val(foo); }); }); |
the Jsfidle bellow will show the live usage of the code presented above
you can replace [2,2,2,2,2]
with any number at all of your choice depending on the series you want to acheive, in the case of a class in an input declare the field like this $('.Your_Field_Key').keyup(function() {
please note the dot before the field identification.
Leave a comment