我正在创建一个网页,其中我有一个输入文本字段,我想只允许数字字符,如(0,1,2,3,4,5…9)0-9。
我如何使用jQuery做到这一点?
我正在创建一个网页,其中我有一个输入文本字段,我想只允许数字字符,如(0,1,2,3,4,5…9)0-9。
我如何使用jQuery做到这一点?
当前回答
/**
Makes the textbox to accept only numeric input
*/
(function($) {
$.fn.allowOnlyNumeric = function() {
/**
The interval code is commented as every 250 ms onchange of the textbox gets fired.
*/
// var createDelegate = function(context, method) {
// return function() { method.apply(context, arguments); };
// };
/**
Checks whether the key is only numeric.
*/
var isValid = function(key) {
var validChars = "0123456789";
var validChar = validChars.indexOf(key) != -1;
return validChar;
};
/**
Fires the key down event to prevent the control and alt keys
*/
var keydown = function(evt) {
if (evt.ctrlKey || evt.altKey) {
evt.preventDefault();
}
};
/**
Fires the key press of the text box
*/
var keypress = function(evt) {
var scanCode;
//scanCode = evt.which;
if (evt.charCode) { //For ff
scanCode = evt.charCode;
}
else { //For ie
scanCode = evt.keyCode;
}
if (scanCode && scanCode >= 0x20 /* space */) {
var c = String.fromCharCode(scanCode);
if (!isValid(c)) {
evt.preventDefault();
}
}
};
/**
Fires the lost focus event of the textbox
*/
var onchange = function() {
var result = [];
var enteredText = $(this).val();
for (var i = 0; i < enteredText.length; i++) {
var ch = enteredText.substring(i, i + 1);
if (isValid(ch)) {
result.push(ch);
}
}
var resultString = result.join('');
if (enteredText != resultString) {
$(this).val(resultString);
}
};
//var _filterInterval = 250;
//var _intervalID = null;
//var _intervalHandler = null;
/**
Dispose of the textbox to unbind the events.
*/
this.dispose = function() {
$(this).die('change', onchange);
$(this).die('keypress', keypress);
$(this).die('keydown', keydown);
//window.clearInterval(_intervalHandler);
};
$(this).live('change', onchange);
$(this).live('keypress', keypress);
$(this).live('keydown', keydown);
//_intervalHandler = createDelegate(this, onchange);
//_intervalID = window.setInterval(_intervalHandler, _filterInterval);
}
})(jQuery);
上面的$ plugin是从AjaxControlToolkit过滤器文本框extender.js编写的。
然而,有一个行为并没有从AjaxControlToolkit中借用,那就是当用户复制和粘贴任何非数字值时,onchange事件就会触发,文本框就会吞噬这些值。我检查了代码,发现这个onchange在每250ms之后被调用,这是一个性能打击,因此注释了这部分。
其他回答
$(document).ready(function()
{
$("#textBoxId").bind("change",checkInput);
});
function checkInput()
{
// check if $('#textBoxId').val() is under your constraints
// then change its value, removing the last character
// since this event will be called each time you
// type a character
}
你可以尝试HTML5数字输入:
<input type="number" value="0" min="0">
对于不兼容的浏览器,可以使用Modernizr和Webforms2。
/**
Makes the textbox to accept only numeric input
*/
(function($) {
$.fn.allowOnlyNumeric = function() {
/**
The interval code is commented as every 250 ms onchange of the textbox gets fired.
*/
// var createDelegate = function(context, method) {
// return function() { method.apply(context, arguments); };
// };
/**
Checks whether the key is only numeric.
*/
var isValid = function(key) {
var validChars = "0123456789";
var validChar = validChars.indexOf(key) != -1;
return validChar;
};
/**
Fires the key down event to prevent the control and alt keys
*/
var keydown = function(evt) {
if (evt.ctrlKey || evt.altKey) {
evt.preventDefault();
}
};
/**
Fires the key press of the text box
*/
var keypress = function(evt) {
var scanCode;
//scanCode = evt.which;
if (evt.charCode) { //For ff
scanCode = evt.charCode;
}
else { //For ie
scanCode = evt.keyCode;
}
if (scanCode && scanCode >= 0x20 /* space */) {
var c = String.fromCharCode(scanCode);
if (!isValid(c)) {
evt.preventDefault();
}
}
};
/**
Fires the lost focus event of the textbox
*/
var onchange = function() {
var result = [];
var enteredText = $(this).val();
for (var i = 0; i < enteredText.length; i++) {
var ch = enteredText.substring(i, i + 1);
if (isValid(ch)) {
result.push(ch);
}
}
var resultString = result.join('');
if (enteredText != resultString) {
$(this).val(resultString);
}
};
//var _filterInterval = 250;
//var _intervalID = null;
//var _intervalHandler = null;
/**
Dispose of the textbox to unbind the events.
*/
this.dispose = function() {
$(this).die('change', onchange);
$(this).die('keypress', keypress);
$(this).die('keydown', keydown);
//window.clearInterval(_intervalHandler);
};
$(this).live('change', onchange);
$(this).live('keypress', keypress);
$(this).live('keydown', keydown);
//_intervalHandler = createDelegate(this, onchange);
//_intervalID = window.setInterval(_intervalHandler, _filterInterval);
}
})(jQuery);
上面的$ plugin是从AjaxControlToolkit过滤器文本框extender.js编写的。
然而,有一个行为并没有从AjaxControlToolkit中借用,那就是当用户复制和粘贴任何非数字值时,onchange事件就会触发,文本框就会吞噬这些值。我检查了代码,发现这个onchange在每250ms之后被调用,这是一个性能打击,因此注释了这部分。
你可以使用一个简单的JavaScript正则表达式来测试纯数字字符:
/^[0-9]+$/.test(input);
如果输入是数字,则返回true,否则返回false。
或事件键码,简单使用如下:
// Allow: backspace, delete, tab, escape, enter, ctrl+A and .
if ($.inArray(e.keyCode, [46, 8, 9, 27, 13, 110, 190]) !== -1 ||
// Allow: Ctrl+A
(e.keyCode == 65 && e.ctrlKey === true) ||
// Allow: home, end, left, right
(e.keyCode >= 35 && e.keyCode <= 39)) {
// let it happen, don't do anything
return;
}
var charValue = String.fromCharCode(e.keyCode)
, valid = /^[0-9]+$/.test(charValue);
if (!valid) {
e.preventDefault();
}
重构了已接受的答案,因此不再需要使用注释,因为我讨厌注释。这也更容易用茉莉花进行测试。
allowBackspaceDeleteTabEscapeEnterPress: function(event){
return ($.inArray(event.keyCode, [46, 8, 9, 27, 13, 190]) >= 0);
},
allowContorlAPress: function(event){
return (event.keyCode == 65 && event.ctrlKey === true)
},
allowHomeEndLeftRightPress: function(event){
return (event.keyCode >= 35 && event.keyCode <= 39)
},
theKeyPressedIsEditRelated: function (event) {
return (this.allowBackspaceDeleteTabEscapeEnterPress(event)
|| this.allowContorlAPress(event)
|| this.allowHomeEndLeftRightPress(event));
},
isNotFromTheNumKeyPad: function (event) {
return (event.keyCode < 96 || event.keyCode > 105);
},
isNotFromTopRowNumberKeys: function (event) {
return (event.keyCode < 48 || event.keyCode > 57);
},
theKeyIsNonNumeric: function (event) {
return (event.shiftKey
|| (this.isNotFromTopRowNumberKeys(event)
&& this.isNotFromTheNumKeyPad(event)));
},
bindInputValidator: function(){
$('.myinputclassselector').keydown(function (event) {
if(this.validateKeyPressEvent(event)) return false;
});
},
validateKeyPressEvent: function(event){
if(this.theKeyPressedIsEditRelated(event)){
return;
} else {
if (this.theKeyIsNonNumeric(event)) {
event.preventDefault();
}
}
}