HTML number input issues with decimal seperator

Viewed 549

I've some issues with decimal input on iOS using the numeric keypad. I have the following HTML:

$('#number').keyup(function() {
  $('#log').prepend('<p>Input: ' + $(this).val() + '</p>');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="number" inputmode="decimal" id="number">
<p>
  Input as number:
  <div id="log"></div>
</p>

This is working as expected in Chrome browser, Android etc., but on iOS there is some issues. If I set the Region to e.g. Denmark (comma decimal seperator) but the Language to English (UK) (point decimal seperator), the number pad gives me a comma decimal seperator, but I seems that the HTML/JS does not support this. If I input e.g. 12,3 the value of the input field becomes empty when I use the comma.

How can I fix this?

iOS demo

When Region is Denmark and Language is Danish, it's all working as expected.

The code and demo is available on this StackBlitz: https://decimal-input-ios.stackblitz.io

5 Answers

I found some workaround, you can replace , with . every time that it is being typed:

let prevNum = "";

$('#number').on("keyup", function (e) {
    if (e.keyCode == 188) {
        $(this).val(prevNum + ".");
    }
    
    prevNum = $(this).val();

    $('#log').prepend('<p>Input: ' + $(this).val() + '</p>');
});

Can you please try to add lang="en" it should change by adding a lang attribute

<input type="number" inputmode="decimal" id="number" lang="en">

This is a cheat, but after reading several similar posts about it, I'm not sure you have too many options. If you don't need the (usually inconsequential) up/down ticks, you can just use a 'text' input with a pattern. The pattern will tell iOS to use the number pad despite this being a 'text' input.

$('#number').keyup(function(evt) {
  $('#log').prepend('<p>Input: ' + $(this).val() + '</p>');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" inputmode="decimal" id="number" pattern="[0-9.,]+">
<p>Input as number:</p>
  <div id="log"></div>

Use parseFloat() to make the value a float

$('#number').keyup(function() {
  $('#log').prepend('<p>Input: ' + parseFloat($(this).val()) + '</p>');
});
<html lang="en-GB">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="number" inputmode="decimal" id="number">
<p>
  Input as number:
  <div id="log"></div>
</p>
</html>

I cannot test since I do not own any IOS device...

But you said:

When Region is Denmark and Language is Danish, it's all working as expected.

So why not just change the whole page language on that specific input focus and restore it on blur? That would be:

$("#number").on("focus", function(){
  $("html").attr("lang", "da");
});

$("#number").on("blur", function(){
  $("html").attr("lang", "en");
});

It worths a try ;)

Related