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

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

This jsfiddle demonstrates the following issue.

The simplest example is:


console.log(document         


        
相关标签:
2条回答
  • 2021-01-17 14:24

    You're not supposed to use <input type=number> for things that are not numbers (in very mathematical sense—it won't work for phone numbers or zip codes either) and clearing of the value is deliberate.

    You can test whether device supports type=number and attach your fallback only if it doesn't:

    var input = document.createElement('input');
    input.setAttribute('type','number');
    if (input.type != 'number') { // JS property won't reflect DOM attribute
       polyfill_number();
    }
    

    Alternatively (especially if your number is a zip code, serial number, etc.) you can use:

    <input type=text pattern="[0-9]*">
    

    and this will change the keyboard too.

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

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