封装成onlyNum(),onlyAlpha()和onlyNumAlpha()3个Jquery扩展方法,方便复用,由于里面一些JS代码涉及到了"禁用输入法,获取剪切板的内容",而"禁用输入法,获取剪切板的内容"只能在IE浏览器下才有效,对于别的浏览器是无效的,因此这三个方法只适合在IE浏览器下使用才有效
一、限制只能输入数字
// ----------------------------------------------------------------------// <summary>// 限制只能输入数字// </summary>// ----------------------------------------------------------------------$.fn.onlyNum = function () {$(this).keypress(function (event) {var eventObj = event || e;var keyCode = eventObj.keyCode || eventObj.which;if ((keyCode >= 48 && keyCode <= 57))return true;elsereturn false;}).focus(function () {//禁用输入法this.style.imeMode = 'disabled';}).bind("paste", function () {//获取剪切板的内容var clipboard = window.clipboardData.getData("Text");if (/^\d+$/.test(clipboard))return true;elsereturn false;});};
二、限制只能输入字母
// ----------------------------------------------------------------------// <summary>// 限制只能输入字母// </summary>// ----------------------------------------------------------------------$.fn.onlyAlpha = function () {$(this).keypress(function (event) {var eventObj = event || e;var keyCode = eventObj.keyCode || eventObj.which;if ((keyCode >= 65 && keyCode <= 90) || (keyCode >= 97 && keyCode <= 122))return true;elsereturn false;}).focus(function () {this.style.imeMode = 'disabled';}).bind("paste", function () {var clipboard = window.clipboardData.getData("Text");if (/^[a-zA-Z]+$/.test(clipboard))return true;elsereturn false;});};
三、 限制只能输入数字和字母
// ----------------------------------------------------------------------// <summary>// 限制只能输入数字和字母// </summary>// ----------------------------------------------------------------------$.fn.onlyNumAlpha = function () {$(this).keypress(function (event) {var eventObj = event || e;var keyCode = eventObj.keyCode || eventObj.which;if ((keyCode >= 48 && keyCode <= 57) || (keyCode >= 65 && keyCode <= 90) || (keyCode >= 97 && keyCode <= 122))return true;elsereturn false;}).focus(function () {this.style.imeMode = 'disabled';}).bind("paste", function () {var clipboard = window.clipboardData.getData("Text");if (/^(\d|[a-zA-Z])+$/.test(clipboard))return true;elsereturn false;});};
使用方法:首先在画面加载完成之后编写如下的JS脚本
$(function () {// 限制使用了onlyNum类样式的控件只能输入数字$(".onlyNum").onlyNum();//限制使用了onlyAlpha类样式的控件只能输入字母$(".onlyAlpha").onlyAlpha();// 限制使用了onlyNumAlpha类样式的控件只能输入数字和字母$(".onlyNumAlpha").onlyNumAlpha();});
用户永远没有机会去犯错
$.fn.onlyNum = function () {$(this).focus(function () {this.value = this.value.replace(/\D/g, '');}).blur(function () {this.value = this.value.replace(/\D/g, '');}).bind("cut copy paste", function (e) {alert('此选项复制粘贴功能被禁用');e.preventDefault();});};// 限制使用了onlyNum类样式的控件只能输入数字$("#SearchDetail_TempProductId").onlyNum();