<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> </head> <body> <form action="" novalidate> <input type="text" autocomplete="off" id="price" autofocus="autofocus" onkeyup="value=value.replace(/[^\d^\.]+/g,'')"> </form> </body> </html>
以上代碼其實不能保證只輸入一個小數點,要想只輸入一個小數點必須加上
replace('.','$#$').replace(/\./g,'').replace('$#$','.') // 這里用到了普通字符串的替換
現在可以再測試下了!
<input type="text" autocomplete="off" id="price" autofocus="autofocus" onkeyup="value=value.replace(/[^\d^\.]+/g,'').replace('.','$#$').replace(/\./g,'').replace('$#$','.')">
補充: 只能輸入數字和一個小數點的正則表達式
var reg = /^\d+$|^\d*\.\d+$/g; reg.test(val) 用於判斷
