Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

javascript - HTML input that takes only numbers and the + symbol

I am trying to build a custom text input for phone numbers that accepts only numbers and the plus (+) symbol; all other characters need to be discarded and not shown on the field.

I am trying to do this using an event handler (onkeydown/onkeypress) and discarding inputs corresponding to other keys. However, I can't figure out a cross-browser way to do it. Here are the approaches that I have tried and don't work:

  • Using the onkeypress event and looking at event.key to figure out which key was pressed: doesn't work on Chrome (see http://caniuse.com/keyboardevent-key). Is there any cross-browser workaround?

  • Using the onkeycode event and looking at event.keyCode: does not work when we need to press multiple keys to print a character (for instance, an English keyboard layout requires pressing Shift and = to give +). Furthermore, it allows characters such as !@#$%?&*() to appear, as these appear when pressing Shift and a number. (This is the approach followed in JavaScript keycode allow number and plus symbol only, but it does not help me much ;))

  • Using the HTML pattern attribute: this does not really seem to prevent people from writing whatever they feel like.

Thanks!

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

There is another solution, you can use Array.prototype.filter() to remove the bad characters, and Array.prototype.join() to recreate the string before insert it into the input.

You can use oninput event. It execute a JavaScript when a user writes something in an <input> field.


See example below

var inputEl = document.getElementById('tel');
var goodKey = '0123456789+ ';

var checkInputTel = function(e) {
  var key = (typeof e.which == "number") ? e.which : e.keyCode;
  var start = this.selectionStart,
    end = this.selectionEnd;

  var filtered = this.value.split('').filter(filterInput);
  this.value = filtered.join("");

  /* Prevents moving the pointer for a bad character */
  var move = (filterInput(String.fromCharCode(key)) || (key == 0 || key == 8)) ? 0 : 1;
  this.setSelectionRange(start - move, end - move);
}

var filterInput = function(val) {
  return (goodKey.indexOf(val) > -1);
}

inputEl.addEventListener('input', checkInputTel);
<input type='tel' id='tel' />

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...