Keydown event issue on HTML textbox

前端 未结 4 888
清歌不尽
清歌不尽 2021-01-15 03:05

I have a field that accepts the year, so I have created

input type=\"number\" 

and implemented keydown event to restrict

4条回答
  •  独厮守ぢ
    2021-01-15 04:00

    So I have moved my code to input[type=tel] and Updated JSFiddle

    If you check, I have added 2 events

    • Keydown to restrict from entering any invalid key.
    • Blur event to check if entered value is number only or not.

    Now you might be thinking, if I have already restricted user to enter only number, how can he enter incorrect value.

    Explanation

    In my implementation, I have used keydown and using keycode, I'm allowing/blocking. Interesting case is when user press and holds shift key. Now on keydown, I get same keycode but value is different(A special character). So checking the integrity on blur.

    A better way would have been handling keypress and keydown together and I'll update fiddle and update my answer, but for now I guess this has solved my problem.

    Thanks you all for all comments/answer. Also kindly let me know if there are any better ways to implement.

提交回复
热议问题