jQuery 限制數字輸入
之前找的 plugin 有點雞婆,還會處理掉數字開頭的 0 ,所以再找一個不去判斷要把前面給去的 plugin ,整段 code 在下。
引入後再去使用就好了,除了整數外也可以限制輸入的格式為帶小數點的數字。
原文連結:
Writing a jQuery plugin to allow only numeric or decimal input
- (function($){
- $.fn.decimalOnly = function() {
- $(this).keydown(function(event) {
- // Allow: backspace, delete, tab, escape, and enter
- if ( event.keyCode == 46 || event.keyCode == 8 || event.keyCode == 9 || event.keyCode == 27 || event.keyCode == 13 ||
- // Allow: Ctrl+A
- (event.keyCode == 65 && event.ctrlKey === true) ||
- // Allow: home, end, left, right
- (event.keyCode >= 35 && event.keyCode <= 39)
- ) {
- // let it happen, don't do anything
- return;
- } else
- if (event.keyCode == 190) { // period
- if ($(this).val().indexOf('.') !== -1) // period already exists
- event.preventDefault();
- else
- return;
- } else {
- // Ensure that it is a number and stop the keypress
- if (event.shiftKey || (event.keyCode < 48 || event.keyCode > 57) && (event.keyCode < 96 || event.keyCode > 105 )) {
- event.preventDefault();
- }
- }
- });
- }
- $.fn.numericOnly = function() {
- $(this).keydown(function(event) {
- // Allow: backspace, delete, tab, escape, and enter
- if ( event.keyCode == 46 || event.keyCode == 8 || event.keyCode == 9 || event.keyCode == 27 || event.keyCode == 13 ||
- // Allow: Ctrl+A
- (event.keyCode == 65 && event.ctrlKey === true) ||
- // Allow: home, end, left, right
- (event.keyCode >= 35 && event.keyCode <= 39)
- ) {
- // let it happen, don't do anything
- return;
- } else {
- // Ensure that it is a number and stop the keypress
- if (event.shiftKey || (event.keyCode < 48 || event.keyCode > 57) && (event.keyCode < 96 || event.keyCode > 105 )) {
- event.preventDefault();
- }
- }
- });
- }
- })(jQuery);
引入後再去使用就好了,除了整數外也可以限制輸入的格式為帶小數點的數字。
- $("#age").numericOnly();
- $("#weight").decimalOnly();
原文連結:
Writing a jQuery plugin to allow only numeric or decimal input
留言