<!DOCTYPE html>
<html lang="zh">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script>
//只能入力数字
function keepNum(obj){
//先把非数字的都替换掉
obj.value = obj.value.replace(/[^\d]/g,"");
}
// 只能入力数字和小数点
function keepNumOrDecimal(obj) {
//先把非数字的都替换掉,除了数字和.
obj.value = obj.value.replace(/[^\d.]/g,"");
//必须保证第一个为数字而不是.
obj.value = obj.value.replace(/^\./g,"");
//保证只有出现一个.而没有多个.
obj.value = obj.value.replace(/\.{2,}/g,".");
//保证.只出现一次,而不能出现两次以上
obj.value = obj.value.replace(".","$#$").replace(/\./g,"").replace("$#$",".");
}
</script>
</head>
<body>
<label>只能入力数字: <input type="text" onkeyup=keepNum(this) maxlength="5"></label>
<br>
<label>只能入力数字或小数点,首位必须是数字,并且.只能出现一次: <input type="text" onkeyup=keepNumOrDecimal(this) maxlength="5"></label>
</body>
</html>
* maxlength设置文本看入力最大长度