Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting the value of a HTML5 number input

I'm using one of the new HTML5 input types, number:

<input type="number" />

In Opera, which is the only desktop browser I know of which currently recognises it, it renders it as such:

enter image description here

The problem I'm facing is one of validation. If a user types something invalid into the field, eg: "abc", the value returned by myInput.value is an empty string. This makes it impossible to tell whether the user left the field blank, or if they entered some incorrect data. Is there any way to get the real value of the field?

like image 427
nickf Avatar asked Jun 22 '10 06:06

nickf


People also ask

How do I get the value of an HTML input?

Use document. getElementById(id_name) to Get Input Value in JavaScript. We give the id property to our Dom input element, and then use document. getElementById(id_name) to select DOM input element, you can simply use the value property.

How do you find the value of a number?

The value refers to the worth of each digit depending on where it lies in the number. We calculate it by multiplying the place value and face value of the digit. For instance: If we consider the number 45. Here digit 4 is in the tens column.


1 Answers

The HTML5 draft defines:

The value sanitization algorithm is as follows: If the value of the element is not a valid floating point number, then set it to the empty string instead.

Reference1

I suppose you'd have use a default value of "0" to make sure the field was left untouched or if something invalid was entered, since there seems to be no obvious way to differentiate the two.

After reading up validation specs and some testing (in Opera 10.54) I concluded that:

<input id="email" type="email" value="blah">
document.getElementById("email").validity.typeMismatch // True

Doesn't work on <input type="number">. Not sure if it's supposed to, or if it's a work in progress. The property does however exist, though it always returns False.

Read more2

You can also set a custom validation method Reference3

like image 157
Daniel Avatar answered Oct 12 '22 01:10

Daniel