html:
<input type = "text" class = "amount"/>
js:
$(function() {
$('.amount').each(function() {
initNumberText($(this))
})
})
function initNumberText(element) {
element.keyup(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[0-9]/g,'0'); //不允许输入以0开头的数字
$(this).val(tmptxt);
}).bind("paste",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[0-9]/g,'0'); //不允许输入以0开头的数字
$(this).val(tmptxt);
});
}