Thoughts on life, liberty, and information technology

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))
			$(this).val('');
		else {
			val = parseInt(val);
			if (min != undefined && val  parseInt(max))
				$(this).val(max);
		}
	});
});

Leave a comment