Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using currency symbols and commas in an input of type number

The best iOS keyboard for entering USD currency values (pictured below) includes numbers 0-9, the decimal symbol, the comma symbol, and the dollar sign. As far as I know, the only way to get this keyboard on Mobile Safari is to use <input type="number">.

Unfortunately, iOS currently has built-in validation for the number input type which screens out commas and dollar symbols. Since this validation "feature" is embedded in the browser and Mobile Safari hasn't yet implemented the novalidate directive, there is currently no way to do this validation manually.

Using <input type="text"> would obviously solve the validation problem, but it also would bring up the regular alpha keyboard, which is not acceptable for my current project (a financial calculator).

I'm on the verge of doing something crazy, like using JavaScript to quickly switch the type from number to text after the input receives focus. I'm grasping at straws here. Any ideas?

enter image description here

like image 897
David Jones Avatar asked Jan 18 '26 21:01

David Jones


1 Answers

For now, JavaScript is the only solution. Here's the simplest way to do it (using jQuery):

HTML

<input type="text">

JavaScript

$('input[type="text"]').on('touchstart', function() {
  $(this).attr('type', 'number');
});

$('input[type="text"]').on('keydown blur', function() {
  $(this).attr('type', 'text');
});

The idea is simple. The input starts off and ends up with type="text", but it briefly becomes type="number" on the touchstart event. This causes the correct iOS keyboard to appear. As soon as the user begins to enter any input or leave the field, the input becomes type="text" once again, thus circumventing the validation.

There's one downside to this method. When the user returns to an input that has already been filled out, the input will be lost (if it doesn't validate). This means the user won't be able to go back and edit previous fields. In my case, this isn't all that bad because the user may want to use the calculator over and over again with different values, so automatically deleting the input will save them a few steps. However, this may not be ideal in all cases.

like image 93
David Jones Avatar answered Jan 20 '26 11:01

David Jones



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!