2

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?

Community
  • 1
  • 1
Yang
  • 7,712
  • 9
  • 48
  • 65
  • Mobile browsers usually do not register `keypress` event. `keydown` or `keyup` however should work but you only need to separate different events in first argument of `$.on()` with a space. There is no need for a comma. – josephting Dec 01 '16 at 06:00
  • You also need to check this, when i go to the end(caret at the end) and press `del` key, it keeps adding hyphens. – Jones Joseph Dec 01 '16 at 06:03
  • @josephting Thank you for the reply. It works on my phone, but not pad. Do you know why? – Yang Dec 01 '16 at 06:10
  • @JonesVinothJoseph Thank you, I have fixed it. – Yang Dec 01 '16 at 06:13
  • @josephting The new URL is https://jsfiddle.net/f99obu18/4/. – Yang Dec 01 '16 at 06:13

1 Answers1

2

jQuery plugin masked-input-plugin may help.

With the plugin, change your code to:

$("form input").mask("9999999999",{placeholder:"-"});
Yang
  • 7,712
  • 9
  • 48
  • 65
Chiu
  • 374
  • 2
  • 10