开发者

Only allow numbers in an input with javascript and allow copy and paste?

开发者 https://www.devze.com 2023-01-08 00:04 出处:网络
I\'m using this function to only allow numbers in a text input. $(\'input\').bind(\'keydown\', function(e) {

I'm using this function to only allow numbers in a text input.

$('input').bind('keydown', function(e) {

    var key = e.charCode || e.keyCode || 0;

    return (
         key == 8 ||
         key == 9 ||
         key == 46 ||
         (key >= 37 &&开发者_C百科amp; key <= 40) ||
         (key >= 48 && key <= 57) ||
         (key >= 96 && key <= 105));
});

How would I also allow copy and paste? I've tried adding keycode 17 for control but it still doesn't work.

Is there something special you have to do for key combinations?

Thanks


You better off with something like:

$('input').bind('keyup', function(e) {
  this.value = this.value.replace(/[^0-9]/g,'');
});

Or you can also use the change event. In this case no matter how the data gets into the field it will be validated (and non numeric input removed). ​


There is input event which is more powerful/flexible than keypress, keydown or change, that reacts on any type of change: program or user type such as key presses or copy/paste events.

// Initial valid input state
let prevValue = ''
let prevSelectionStart = 0

function allowNumbersOnly(event) {
  const input = event.target
  let value = event.target.value

  // Check if value is number
  let isValid = +value == +value

  if (isValid) {
    // preserve input state
    prevValue = value
    prevSelectionStart = input.selectionStart
  } else {
    // restore previous valid input state.
    // we have to fire one more Input event in  order to reset cursor position.
    var resetEvent = new InputEvent('input')
    input.value = prevValue
    input.selectionStart = prevSelectionStart
    input.selectionEnd = prevSelectionStart
    input.dispatchEvent(resetEvent)
  }
}
<input type="text" oninput="allowNumbersOnly(event)">


Keep a record of the last keycode pressed. Since you're using onkeydown, a cmd-v would show up as an event with keycode 224 (cmd) and then an event with keycode 86 (v). If the previous key matches cmd and the latter v, allow it through.

(you would probably check for ctrl for Windows/Linux pasters as well)

0

精彩评论

暂无评论...
验证码 换一张
取 消