本文實例講述了jQuery實現只允許輸入數字和小數點的方法。分享給大家供大家參考,具體如下:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN""http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head><script src="jquery.min.js" type="text/javascript"></script><script type="text/javascript">//示例代碼://只允許輸入數字與.:<input type="text" name="test" id="test" onkeydown="checkKeyForFloat(this.value,event)" style="ime-mode: disabled" />//只允許輸入數字 :<input type="text" name="test2" id="test2" onkeydown="checkKeyForNum(this.value,event)" style="ime-mode: disabled" />//只允許輸入數字與小數點function checkKeyForFloat(value, e) { var isOK = false; var key = window.event ? e.keyCode : e.which; if ((key > 95 && key < 106) || //小鍵盤上的0到9 (key > 47 && key < 60) || //大鍵盤上的0到9 (key == 110 && value.indexOf(".") < 0) || //小鍵盤上的.而且以前沒有輸入. (key == 190 && value.indexOf(".") < 0) || //大鍵盤上的.而且以前沒有輸入. key == 8 || key == 9 || key == 46 || key == 37 || key == 39 //不影響正常編輯鍵的使用(8:BackSpace;9:Tab;46:Delete;37:Left;39:Right)) { isOK = true; } else { if (window.event) //IE { e.returnValue = false; //event.returnValue=false 效果相同. } else //Firefox { e.preventDefault(); } } return isOK;}//只允許輸入數字function checkKeyForInt(value, e) { var isOK = false; var key = window.event ? e.keyCode : e.which; if ((key > 95 && key < 106) || //小鍵盤上的0到9 (key > 47 && key < 60) || //大鍵盤上的0到9 key == 8 || key == 9 || key == 46 || key == 37 || key == 39 //不影響正常編輯鍵的使用(8:BackSpace;9:Tab;46:Delete;37:Left;39:Right)) { isOK = true; } else { if (window.event) //IE { e.returnValue = false; //event.returnValue=false 效果相同. } else //Firefox { e.preventDefault(); } } return isOK;}//設置有自定義屬性 dtype 的文本框 允許輸入的范圍function setDType() { $(":text[dtype]").each(function () { var dtype = $(this).attr("dtype"); var isOK = true; switch (dtype) { case "number": $(this).css("ime-mode", "disabled").keydown(function (event) { isOK = checkKeyForFloat($(this).val(), event); if (!isOK) { //$(this).SuperFocus("", 500); } return isOK; }); break; default: break; } });}</script><script type="text/javascript">$(function () { setDType();});</script></head><body>年齡: <input type="text" maxlength="3" onkeydown="checkKeyForInt(this.value,event)" style="ime-mode: disabled"/><br />身高:<input type="text" maxlength="5" dtype="number" /></body></html>
更多關于jQuery相關內容感興趣的讀者可查看本站專題:《jQuery拖拽特效與技巧總結》、《jQuery擴展技巧總結》、《jQuery常見經典特效匯總》、《jQuery動畫與特效用法總結》、《jquery選擇器用法總結》及《jQuery常用插件及用法總結》
希望本文所述對大家jQuery程序設計有所幫助。
新聞熱點
疑難解答