Keydown event issue on HTML textbox

前端 未结 4 860
清歌不尽
清歌不尽 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 03:43

    May be this will work , you can use the Regular Express to validate only number and

    ^[0-9\.\-\/]+$
    

    and also you can use the .length method to insure that you have specific length

    0 讨论(0)
  • 2021-01-15 03:44

    You can't submit an invalid value in this case:

    <form>
      <input type=number min=0 max=9999 required />
      <input type=submit value=Submit />
    </form>

    0 讨论(0)
  • 2021-01-15 03:58

    HTML:

    <input type="tel" class="year" maxlength="4" data-temp="">
    

    jQuery:

    $(document).on('input', '.year', function(){
        var txt = $(this).val();
        if(isNaN(txt) || txt > 9999){
            $(this).val( $(this).data('temp') );
            return;
        }
        $(this).data('temp', txt);
    });
    

    JSFiddle

    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题