1. 程式人生 > 實用技巧 >在HTML中限制input 輸入框只能輸入純數字

在HTML中限制input 輸入框只能輸入純數字

1.使用onkeyup事件,有bug,那就是在中文輸入法狀態下,輸入漢字之後直接回車,會直接輸入字母

onkeyup = "value=value.replace(/[^\d]/g,'')"

  

2.使用onchange事件,在輸入內容後,只有input喪失焦點時才會得到結果,並不能在輸入時就做出響應

onchange = "value=value.replace(/[^\d]/g,'')"

  

3.使用oninput事件,完美的解決了以上兩種問題,測試暫時還沒有出現其它問題。

oninput = "value=value.replace(/[^\d]/g,'')"

  

素材公社https://www.wode007.com/sites/73209.html 愛圖網https://www.wode007.com/sites/73208.html

程式碼示例

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8" />
    <title>input</title>
</head>
<body>
    只能輸入純數字的輸入框:<input type="text" name="" oninput="value=value.replace(/[^\d]/g,'')">
</body>
</html>

  

注:以上程式碼均已在谷歌、火狐、百度、UC、IE11、360急速、QQ、Edge瀏覽器下測試完畢,請放心使用。