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

前端 未结 2 1355
天命终不由人
天命终不由人 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 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:

    
    

    and this will change the keyboard too.

提交回复
热议问题