Get value of <input type=“number”> with JS when it contains non-numeric characters

前端 未结 2 1361
天命终不由人
天命终不由人 2021-01-17 13:48

This jsfiddle demonstrates the following issue.

The simplest example is:


console.log(document         


        
2条回答
  •  甜味超标
    2021-01-17 14:35

    This is what I was looking for:

    $('input[type=number]').keypress(function(e) {
      if (!String.fromCharCode(e.keyCode).match(/[0-9\.]/)) {
        return false;
      }
    });
    

    I understand preventing user input can be annoying and this still allows invalid input such as 1.2.3

    However in this situation it is exactly what I needed. Hopefully it will be of use to someone else. Thanks to @int32_t for the suggestion.

提交回复
热议问题