Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 696
captainclam Avatar asked Mar 26 '13 00:03

captainclam


People also ask

How check value is numeric or not in JavaScript?

The Number. isInteger() method returns true if a value is an integer of the datatype Number. Otherwise it returns false .


1 Answers

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.

like image 67
captainclam Avatar answered Oct 19 '22 10:10

captainclam