HTML text input allow only numeric input

前端 未结 30 3522
孤街浪徒
孤街浪徒 2020-11-21 04:58

Is there a quick way to set an HTML text input () to only allow numeric keystrokes (plus \'.\')?

30条回答
  •  伪装坚强ぢ
    2020-11-21 05:41

    And one more example, which works great for me:

    function validateNumber(event) {
        var key = window.event ? event.keyCode : event.which;
        if (event.keyCode === 8 || event.keyCode === 46) {
            return true;
        } else if ( key < 48 || key > 57 ) {
            return false;
        } else {
            return true;
        }
    };
    

    Also attach to keypress event

    $(document).ready(function(){
        $('[id^=edit]').keypress(validateNumber);
    });
    

    And HTML:

    
    

    Here is a jsFiddle example

提交回复
热议问题