HTML text input allow only numeric input

前端 未结 30 3442
孤街浪徒
孤街浪徒 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:28

    A short and sweet implementation using jQuery and replace() instead of looking at event.keyCode or event.which:

    $('input.numeric').live('keyup', function(e) {
      $(this).val($(this).val().replace(/[^0-9]/g, ''));
    });
    

    Only small side effect that the typed letter appears momentarily and CTRL/CMD + A seems to behave a bit strange.

提交回复
热议问题