Yang Yang - 1 year ago 139
HTML Question

Restrict HTML input to fixed length digits

I am designing an HTML input to accept phone numbers (10 digits). I want the input form to be pre-filled with '-'s. When users input numbers, the '-'s should be replaced by the actual numbers. Similarly, when users delete numbers, they should be replaced by '-'s.

Here is what I achieved: https://jsfiddle.net/f99obu18/2/.

Javascript code (with jQuery):

$("form input").val("-".repeat(10));
$("form").on('keypress keydown', 'input', function(event) {
// Replaces the "-" while user input.
var index = this.selectionStart;
if (event.keyCode >= 48 && event.keyCode <= 57) {
$(this).val($(this).val().substring(0, index) +
$(this).val().substring(index + 1, $(this).val().length));
setCaretToPos(this, index);
// Adds "-" at the current position for "Backspace."
if (event.keyCode == 8 && index > 0) {
$(this).val($(this).val().substring(0, index) + '-' +
$(this).val().substring(index, $(this).val().length));
setCaretToPos(this, index);
// Adds "-" at the current position for "Delete."
if (event.keyCode == 46) {
$(this).val($(this).val().substring(0, index) + '-' +
$(this).val().substring(index + 1, $(this).val().length));
setCaretToPos(this, index);
return false;

(The setCaretToPos method is taken from jQuery Set Cursor Position in Text Area.)

Question: The solution looks good on my computer, but doesn't work on my phone. Is there standard, re-usable code (e.g., jQuery plugins) for this input validation?

Answer Source

jQuery plugin masked-input-plugin may help.

With the plugin, change your code to:

$("form input").mask("9999999999",{placeholder:"-"});
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download