需求 为避免用户输入非法数据,希望能对某些输入框的输入做限制。这里用价格输入框(只允许输入最多2位小数的非负数值)
来做例子:
1 <input type ="text" id ="price" name ="price" placeholder ="请输入价格(最多2位小数)" required >
键盘事件处理代码(javascript) 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 $(function ( ){ $('#price' ).keypress (onPriceKeypress).keyup (onPriceKeyup); function onPriceKeypress (e ){ var allowKeys = '0123456789+.' ; var keyCode = e.which ; if (code<32 || (code>126 && code<160 )){ return true ; } if (allowKeys.indexOf (String .fromCharCode (code))<0 ){ return false ; } return true ; } function onPriceKeyup (e ){ var $ipt = $(this ), val = $ipt.val (); if (!/^[+\d]?\d*\.?\d{0,2}$/ .test (val)){ $ipt.val (/[+\d]?\d*\.?\d{0,2}/ .exec (val)); } } }
注:
只在input使用pattern属性(如:pattern="[+\d]?\d*\.?\d{0,2}"
)只能限制最后的结果,不能限制输入不当的字符。
把input的type设为number可限制只能输入数字,但无法输入小数。
在有些浏览器(如Firefox)下控制字符也会触发keypress事件,待textinput事件普及后改用该事件就不用做特殊处理了。