Skip to content

Instantly share code, notes, and snippets.

@rightsaidjames
Last active August 29, 2015 14:05
Show Gist options
  • Save rightsaidjames/771256524209a9ba1665 to your computer and use it in GitHub Desktop.
Save rightsaidjames/771256524209a9ba1665 to your computer and use it in GitHub Desktop.
A Pen by James Thomas.

HTML5 input [type='number'] demo

A demonstration of the error handling functionality of the [input type='number'] HTML5 element. In modern browsers non-numeric input will be stripped out.

A Pen by James Thomas on CodePen.

License.

<h1>Demonstration - HTML5 input [type='number'] error handling </h1>
<p>The HTML 5 <em>&lt;input type="number"&gt;</em> attribute is designed to catch invalid characters (e.g. letters, symbols, spaces) and strip them out before they are passed to a JS function or submitted elsewhere. This is useful functionality, but there are inconsistencies between different browsers.</p>
<p>Example inputs:</p>
<ul>
<li>3. 07</li>
<li>4 .67</li>
<li>457ffd</li>
<li>45.</li>
<li>45%$33</li>
</ul>
<p>Different browsers will handle these example inputs differently. If nothing appears next to 'Result:' then the browser is considering the input as invalid (i.e. not a number) instead of stripping out unwanted characters.</p>
<input type="number" id="numberbox" />
<input type="button" value="Test" onclick="numbertest()" />
<p><strong>Result:</strong> <span id="parsed"></span></p>
function numbertest() {
var result = document.getElementById('numberbox').value;
var parsed = document.getElementById('parsed')
parsed.innerHTML = result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment