Skip to content

Instantly share code, notes, and snippets.

@liuzhuan
Created January 17, 2017 10:38
Show Gist options
  • Save liuzhuan/967d50337263ee6a6bf8205184099064 to your computer and use it in GitHub Desktop.
Save liuzhuan/967d50337263ee6a6bf8205184099064 to your computer and use it in GitHub Desktop.
How to force a input field only accept integer?
/**
* 强制输入框只能输入正整数
* @param {string} id 输入框的id
*/
function intInput(id) {
var item = document.querySelector(id);
item.onkeyup = forceInt;
item.onafterpaste = forceInt;
function forceInt() {
this.value = this.value.replace(/[^0-9]+/, '').replace(/^0+/, '');
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment