Search code examples
javascripthtmltextinput

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


This jsfiddle demonstrates the following issue.

The simplest example is:

<input id="number" type="number" value="1">
console.log(document.getElementById('number').value);

This logs 1 as expected. THIS however:

<input id="number" type="number" value="1A">
console.log(document.getElementById('number').value);

Just logs an empty string '', because of the non-numeric character in the value. Some devices+browsers (e.g. Chrome) allow you to enter non-numeric characters in these inputs.

This is annoying because I want the type="number" input for devices that support it (e.g. iPhone, iPad number keyboard). However I want to use javascript to stop dirty input from being entered - which requires fetching the value on keyup - then regex replacing the non-numeric chars.

It appears jQuery's .val() method gives the same result.


Solution

  • 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.