一個表單: <input type="text" class="num" maxNum="100" />
1、如何設定只能輸入整數?
2、如何設定只能輸入數字(整數或小數)?
一開始,用正則表達式來把1命題搞定了,但是第2個卻有點費力!后來百度了一下,終於找到辦法,這里都貼出來讓大家看看,不知道還有沒有BUG,歡迎指正~
一、如何設定只能輸入整數
示例表單: <input type="text" class="num" maxNum="100" />
1 (function ($) { 2 $("input.num").live("keyup",function () { //鍵盤輸入事件 3 CheckNum($(this)); 4 }).bind("paste", function () { //粘貼事件 5 CheckNum($(this)); 6 }).css("ime-mode", "disabled"); 7 })(jQuery); 8 9 function CheckNum(obj) { //驗證整數 10 obj = jQuery(obj); 11 var tmptxt = obj.val().replace(/\D|^/g, ''); //利用正則表達式
12 var maxNum = jQuery.trim(obj.attr("maxNum")); //最大值 13 if (maxNum) { 14 if (parseInt(maxNum) >= parseInt(tmptxt)) { 15 obj.val(tmptxt); 16 } 17 else { 18 obj.val(""); 19 } 20 return; 21 } 22 obj.val(tmptxt); 23 }
二、如何設定只能輸入數字(整數或小數)?
示例表單: <input type="text" class="float" maxNum="100" />
1 (function ($) { 2 $("input.float").live("keyup", function () { //鍵盤輸入事件 3 CheckFloat($(this)); 4 }).bind("paste", function () { //粘貼事件 5 CheckFloat($(this)); 6 }).css("ime-mode", "disabled"); 7 })(jQuery); 8 9 10 function CheckFloat(obj) { //驗證小數 11 obj = jQuery(obj); 12 var tmptxt = obj.val(); 13 if (isNaN(tmptxt) != true) { //利用isNaN()方法 14 var maxNum = jQuery.trim(obj.attr("maxNum")); //最大值 15 if (maxNum) { 16 if (parseFloat(maxNum) >= parseFloat(tmptxt)) { 17 obj.val(tmptxt); 18 } 19 else { 20 obj.val(""); 21 } 22 return; 23 } 24 } 25 else { 26 tmptxt = ""; 27 } 28 obj.val(tmptxt); 29 }
至此,終於搞定了~
PS: 上面的方法是基於jquery的,自己上網淘一個