在表單中,常需限制輸入框只能填數字。以下透過擴充 jQuery 方法 $.fn.integer 與 $.fn.number,分別實作「僅整數」與「整數加小數」的輸入限制,並同時封鎖中文輸入法與貼上功能。
完整程式碼如下:
$(function(){
// 文本框只能輸入數字(不含小數),並屏蔽輸入法和粘貼
$.fn.integer = function() {
$(this).css("ime-mode", "disabled");
this.bind("keypress", function(e) {
var code = (e.keyCode ? e.keyCode : e.which); // 相容火狐、IE
if(!$.browser.msie && (e.keyCode == 0x8)){ // 火狐下允許使用退格鍵
return;
}
return code >= 48 && code <= 57;
});
this.bind("paste", function() {
return false;
});
this.bind("keyup", function() {
if (/(^0+)/.test(this.value)) {
this.value = this.value.replace(/^0*/, '');
}
});
};
// 文本框只能輸入數字(含小數),並屏蔽輸入法和粘貼
$.fn.number = function() {
$(this).css("ime-mode", "disabled");
this.bind("keypress", function(e) {
var code = (e.keyCode ? e.keyCode : e.which); // 相容火狐、IE
if(!$.browser.msie && (e.keyCode == 0x8)){ // 火狐下允許使用退格鍵
return;
}
if(this.value.indexOf(".") == -1){
return (code >= 48 && code <= 57) || (code == 46); // 允許數字與小數點
}else{
return code >= 48 && code <= 57; // 已有小數點後僅允許數字
}
});
this.bind("paste", function() {
return false;
});
this.bind("keyup", function() {
if(this.value.slice(0,1) == "."){
this.value = "";
}
});
this.bind("blur", function(){
if(this.value.slice(-1) == "."){
this.value = this.value.slice(0, this.value.length-1);
}
});
};
});
使用時只要呼叫 $("#myInput").integer(); 或 $("#myInput").number(); 即可套用。integer 僅允許 0-9 的按鍵(keycode 48-57),並在 keyup 時去除前導 0;number 則額外允許一次小數點(keycode 46),並在失焦時移除結尾多餘的小數點,確保輸入內容始終合法。