js限制輸入框只能輸入數字

2022-03-14 13:17:12 字數 1056 閱讀 2836

分享下js限制輸入框中只能輸入數字的方法,包括整數與小數,分享幾個例子,有需要的朋友參考下。

1.使用正規表示式限制輸入框只能輸入數字:

1

<

input

type

="text"

onkeyup

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

onafterpaste

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

name

="f_order"

value

="1"

/>

其中,onafterpaste防止使用者從其它地方

copy

內容貼上到輸入框。

2.輸入框只能輸入字母和下橫線的正規表示式

1

<

input

onkeyup

="this.value=this.value.replace(/[^_a-za-z]/g,'')"

onpaste

="this.value=this.value.replace(/[^_a-za-z]/g,'')"

>

3.輸入框只能輸入字母數字和下橫線的正規表示式 

1

<

input

onkeyup

="this.value=this.value.replace(/[^\w]/g,'')"

onpaste

="this.value=this.value.replace(/[^\w]/g,'')"

>

或者

1

<

input

onkeyup

="this.value=this.value.replace(/[\w]/g,'')"

onpaste

="this.value=this.value.replace(/[\w]/g,'')"

>

限制 input 輸入框只能輸入數字

1 onkeyup value value.replace d g,使用 onkeyup 事件,有 bug 那就是在中文輸入法狀態下,輸入漢字之後直接回車,會直接輸入字母 2 onchange value value.replace d g,使用 onchange 事件,在輸入內容後,只有 inpu...

限制input輸入框只能輸入數字

1 onkeyup value value.replace d g,使用 onkeyup 事件,有 bug 那就是在中文輸入法狀態下,輸入漢字之後直接回車,會直接輸入字母 2 onchange value value.replace d g,使用 onchange 事件,在輸入內容後,只有 inpu...

限制 input 輸入框只能輸入純數字

限制 input 輸入框只能輸入純數字 1 onkeyup value value.replace d g,使用 onkeyup 事件,有 bug 那就是在中文輸入法狀態下,輸入漢字之後直接回車,會直接輸入字母 2 onchange value value.replace d g,使用 onchan...