Forcing the min/max on HTML number inputs

HTML5 has fantastic new features — one of them is type="number" attribute for input tags, which (among other things) restricts the user to only entering numbers (and spawning the number keyboard on mobile phones) and giving a (not always useful) widget that lets you increase/decrease the number. Unfortunately, one piece is missing (at least from most browsers I’ve seen): restricting the input to numbers within the min/max range.

Fortunately, a little JavaScript (via jQuery) can fix that. Add the below to your site, and any input type="number" tags on your site will have their min/max values enforced.

$(function () {
	$('input[type=number]').blur(function() {
		var min = $(this).attr('min');
		var max = $(this).attr('max');
		var val = $(this).val();

		if (isNaN(val))
		else {
			val = parseInt(val);
			if (min != undefined && val < parseInt(min))
			else if (max != undefined && val > parseInt(max))

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes:

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>