How to get the raw value an <input type="number"> field?

JavascriptHtmlValidationInput

Javascript Problem Overview


How can i get the "real" value of an <input type="number"> field?


I have an input box, and i'm using newer HTML5 input type number:

<input id="edQuantity" type="number">

This is mostly supported in Chrome 29:

enter image description here

What i now need is the ability to read the "raw" value the user has entered in the input box. If the user has entered a number:

enter image description here

then edQuantity.value = 4, and all is well.

But if the user enters invalid text, i want to color the input-box red:

enter image description here

Unfortunately, for a type="number" input box, if the value in the text-box is not a number then value returns an empty string:

edQuantity.value = "" (String);

(in Chrome 29 at least)

How can i get the "raw" value of an <input type="number"> control?

i tried looking through Chrome's list of other properties of the input box:

enter image description here

i didn't see anything that resembles the actual input.

Nor could i find a way to tell if the box "is empty", or not. Maybe i could have inferred:

value          isEmpty        Conclusion
=============  =============  ================
"4"            false          valid number
""             true           empty box; not a problem
""             false          invalid text; color it red

Note: You can ignore everything after the horizontal rule; it's just filler to justify the question. Also: don't confuse the example with the question. People might want the answer to this question for reasons other than coloring the box red (One example: converting the text "four" into the latin "4" symbol during the onBlur event)

How can i get the "raw" value of an <input type="number"> control?

Bonus Reading

Javascript Solutions


Solution 1 - Javascript

According to the WHATWG, you shouldn't be able to get the value unless it's valid numeric input. The input number field's sanitization algorithm says the browser is supposed to set the value to an empty string if the input isn't a valid floating point number.

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

By specifying the type (<input type="number">) you're asking the browser to do some work for you. If, on the other hand, you'd like to be able to capture the non-numeric input and do something with it, you'd have to rely on the old tried and true text input field and parse the content yourself.

The W3 also has the same specs and adds:

> User agents must not allow the user to set the value to a non-empty > string that is not a valid floating-point number.

Solution 2 - Javascript

It doesn't answer the question, but the useful workaround is to check

edQuantity.validity.valid

The ValidityState of an object gives clues about what the user entered. Consider a type="number" input with a min and max set

<input type="number" min="1" max="10">

We always want to use .validity.valid.

Other properties only give bonus information:

┌──────────────┬────────┬────────╥───────────┬─────────────────┬────────────────┐
│ User's Input │ .value │ .valid ║ .badInput │ .rangeUnderflow │ .rangeOverflow │
├──────────────┼────────┼────────╫───────────┼─────────────────┼────────────────┤
│ """"truefalsefalsefalse          │ valid because field not marked required
│ "1""1"truefalsefalsefalse          │ 
│ "10""10"truefalsefalsefalse          │
│ "0""0"falsefalsetruefalse          │ invalid because below min
│ "11""11"falsefalsefalsetrue           │ invalid because above max
│ "q"""falsetruefalsefalse          │ invalid because not number
│ "³"""falsetruefalsefalse          │ superscript digit 3"٣"""falsetruefalsefalse          │ arabic digit 3"₃"""falsetruefalsefalse          │ subscript digit 3
└──────────────┴────────┴────────╨───────────┴─────────────────┴────────────────┘

You'll have to ensure that the the browser supports HTML5 validation before using it:

function ValidateElementAsNumber(element)
{
   //Public Domain: no attribution required.
   if ((element.validity) && (!element.validity.valid))
   {
      //if html5 validation says it's bad: it's bad
      return false;
   }
   
   //Fallback to browsers that don't yet support html5 input validation
   //Or we maybe want to perform additional validations
   var value = StrToInt(element.value);
   if (value != null)
      return true;
   else
      return false;
}

Bonus

Spudly has a useful answer that he deleted:

> Just use the CSS :invalid selector for this. > > input[type=number]:invalid { > background-color: #FFCCCC; > } > > This will trigger your element to turn red whenever a non-numeric > valid is entered. > > Browser support for <input type='number'> is about the same as > :invalid, so no problem there. > > Read more about :invalid > here.

Solution 3 - Javascript

input.focus();
document.execCommand("SelectAll");
var displayValue = window.getSelection().toString();

Solution 4 - Javascript

Track all pressed keys based on their key codes

I suppose one could listen to the keyup events and keep an array of all characters entered, based on their keycodes. But it's a pretty tedious task and probably prone to bugs.

http://unixpapa.com/js/key.html

Select the input and get the selection as a string

document.querySelector('input').addEventListener('input', onInput);

function onInput(){
  this.select(); 
  console.log( window.getSelection().toString() )
}

<input type='number'>

All credit to: int32_t

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionIan BoydView Question on Stackoverflow
Solution 1 - Javascriptj08691View Answer on Stackoverflow
Solution 2 - JavascriptIan BoydView Answer on Stackoverflow
Solution 3 - Javascriptint32_tView Answer on Stackoverflow
Solution 4 - JavascriptsandstromView Answer on Stackoverflow