Javascript – Force iOS numeric keyboard with custom / currency pattern

iosjavascriptjquery-mobilekeyboard

Is there a possiblity to force an iOS-device to show the numeric keyboard while using a custom pattern as input type?

my input pattern:

<input id="price" class="numeric" pattern="\d+((\.|,)\d{1,2})?" name="price" 
title="" data-mini="true" data-clear-btn="true" autocomplete="off" autofocus />

I want to type a currency value like '14.99' and show up a keyboard with access to numbers on the iOS device

<input type='number' />
<input pattern='[0-9]*' />
<input pattern='[\d]*' />

are all missing the decimal sign and/or are not validating as number when adding a decimal sign. An alternative way could be a javascript function which is creating the decimal sign on the right place, like pressing 1->2->9->9 in this order creates on keypress() 0.01->0.12->1.29->12.99,
but this requires the input field to be type='text' –> obvious problem here is that the text keyboard is showed when focussing the input field.

How can I solve this issue?

EDIT

Environment:

  • JQM 1.3.2
  • jquery 1.8.2

Best Answer

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.

It looks like Mobile Safari supports the new HTML5 input type attributes of email, number, search, tel, and url. These will switch the keyboard that is displayed. See the type attribute.

So for example, you could do this:

<input type="number" />

And when the input box has focus, the number keyboard is shown (as if the user had the full keyboard and hit the "123" button.

If you really only want numbers, you could specify:

<input type="tel" />

And then the user would get the phone number dialing keypad.

I know this works with Mobile Safari -- I only assume it will work with UIWebView.

http://conecode.com/news/2011/12/mobile-safari-uiwebview-input-types/