Site icon Ryadel

HTML input type number with (localized) decimal values using JQuery

HTML input type number with (localized) decimal values using JQuery

Among the many great features introduced with HTML5 there are the new types added for the <input> elements: these are color, date, datetime-local, email, month, number, range, search, tel, time, url, week. If you're into web design you most certainly know how painful it was to properly support these types by adding drop-down lists, inline calendars and other client-side validation scripts to force the user to insert these kind of values: as of today most of the trouble is gone thanks to these new types, because the web browser will take care of that with a built-in set of good-looking (and standardized) controls.

HTML input type number with (localized) decimal values using JQuery
The input type="date" support in Google Chrome, which even features a handy inline calendar to select the desired day: neat!

Suprisingly enough, one of the most simple cases - the number type - still has some nasty issues if you need to use decimal values. According to W3C specifications, you need to also add the step attribute to support that.  For example, if you want to support two decimal numbers, you can do the following:

That's it, right? Sadly, it's not, unless you want to restrict your website audience to en-US (or to Mozilla Firefox) users only. That's because the input type="number" with decimal steps is only supported with the dot separator in most browsers: the sole exception comes from Mozilla Firefox, which allows commas to be used if the HTML5 is properly localized - for example, using

<body lang="it">

.

Here's the current status of this issue (by browser type), as shown in this GitHub thread:

Input Firefox Chrome IE Edge Safari
123
123.45 (with
. region)
123,45 (with
. region)
123.45 (with
, region)
123,45 (with
, region)
123,456.78
123.456,78
10e-1

This cripples the

<input type="number">

to the point that it cannot be used anytime we need to support an international and/or multilanguage scenario. Whenever you need to do that, the best thing you can do is to revert to a simple

<input type="text">

and validate the user input using JavaScript.

Here's a decent script you can use, which is loosely based from this StackOverflow thread:

Place it at the end of your HTML code (or inside a

$(function() {})

call), then assign the number class to any input you want to validate this way. If you want, you can also uncomment the optional lines to replace commas with dots (or vice versa).

UPDATE: I created a JSFiddle with the above code if you want to test it online.

That's it for now: happy coding!

 

Exit mobile version