DIV CSS 佈局教程網

用 jQuery 限制輸入框只能填數字(含禁止貼上與拖曳)
編輯:JQuery特效代碼     

表單驗證固然重要,但直接從輸入端限制能省下不少來回。以下示範如何讓欄位只接受數字。

基本版:只允許數字

$("#money").bind("propertychange",function() {
if(""!=this.value){
var str = this.value.replace(/(^\s*)|(\s*$)/g, "");
if(this.value != str )
this.value = str;
}
if( isNaN(Number(this.value)))
this.value = this.value.replace(/[\D]/,'');
});

這裡把事件綁在 id 為 money 的欄位上:先去掉前後空白,再用 \D 把所有非數字字元清掉。

連小數點也一併排除

$("#phone").bind("propertychange", function() {
if(""!=this.value){
var str = this.value.replace(/(^\s*)|(\s*$)/g, "");
if(this.value != str )
this.value = str;
}
if (this.value.indexOf('.') != -1) {
this.value = this.value.replace(/[\.]/, '');
this.focus();
}
if (isNaN(Number(this.value))) {
this.value = ($.trim(this.value)).replace(/[\D]/, '');
this.focus();
}
});

再補上關閉輸入法

單純攔字元還不夠,使用者仍可能用中文輸入法輸入。透過 CSS 的 ime-mode:disabled 就能關掉輸入法。

禁止貼上與拖曳

建立一個 CSS 類:

.TextBox_NotDragpaste
{
ondragenter:expression(ondragenter=function(){return false;});
onpaste:expression(onpaste=function(){return false;});
}

若還需要禁用中文輸入,多加一行即可:

.TextBox_NotDragpaste
{
ime-mode:disabled;
ondragenter:expression(ondragenter=function(){return false;});
onpaste:expression(onpaste=function(){return false;});
}

提醒兩點:CSS expression 是 IE 專屬語法,且有效能與安全性疑慮,正式環境建議改用 JS 綁定 onpaste 與 ondragenter 事件並 return false;另外 propertychange 同樣是 IE 專屬事件,跨瀏覽器時可改用 input 事件,效果相同而相容性更好。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved