在JavaScript中,可以利用if語句和keycode來設置文本框不能輸入數(shù)字,0到9的keycode值為48到57,只要控制文本框內的keycode值不在該范圍內,語法為“if(charCode>46&&charCode<58)”。
本教程操作環(huán)境:windows10系統(tǒng)、javascript1.8.5版、Dell G3電腦。
javascript怎樣設置文本框不能輸入數(shù)字
數(shù)字0-9keycode的值為48-57,只要在JavaScript中設置文本框中輸入keycode的值在這個范圍內就就取消此行為,以此就可以實現(xiàn)文本框不能輸入數(shù)字。
示例如下:
或者:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> </head> <body> <input type="text" id="test"> <script type="text/javascript"> window.onload=function(){ document.getElementById('test').addEventListener('keypress',function(e){ var charCode=e.charCode; if(charCode>46&&charCode<58) /*0-9 的charcode*/ e.preventDefault(); }); } </script> </body> </html>
輸出結果與上述結果相同,文本框內無法輸入數(shù)字。
【