文本框中只能输入数字

html:

<input type = "text" class = "amount"/>

js:

$(".amount").on('input',function() {
       var tmptxt = $(this).val();
        tmptxt = tmptxt.replace(/[^\d.]/g,"");  //清除“数字”和“.”以外的字符
        tmptxt = tmptxt.replace(/^\./g,"");  //验证第一个字符是数字而不是.
        tmptxt = tmptxt.replace(/\.{2,}/g,"."); //只保留第一个. 清除多余的.
        tmptxt = tmptxt.replace(".","$#$").replace(/\./g,"").replace("$#$",".");
        tmptxt = tmptxt.replace(/^0{1,}/g,'0'); //不允许输入多个0开头的数字
        $(this).val(tmptxt);
      });

猜你喜欢

转载自blog.csdn.net/weixin_43473995/article/details/88736666