Cursor moves to front when entering decimal into a number field in phoenix liveview

First of all, absolutely loving phoenix liveview! Running into a small issue though:

I have a “controlled” field (terminology borrowed from react world) in which form changes are sent back to the server using phx-change and the value is displayed using the “value” attribute on the input. The input is of type “number.”

When typing into the field, entering a decimal point sometimes causes the decimal point to be erased and the cursor to move to the beginning of the field. This makes it difficult to enter a field with a decimal value.

Changing the type to “text” solves the problem but this means that phones will display the full keyboard rather than a number pad which is undesirable. It would be great to be able to use the number type for this field.

Has anyone experienced this before? Any known workarounds?

You can use the pattern or inputmode attribute to force certain keyboards on mobile.

2 Likes

inputmode worked well. I stumbled onto a potentially relevant piece in react code:

    // In Chrome, assigning defaultValue to certain input types triggers input validation.
    // For number inputs, the display value loses trailing decimal points. For email inputs,
    // Chrome raises "The specified value <x> is not a valid email address".
    //
    // Here we check to see if the defaultValue has actually changed, avoiding these problems
    // when the user is inputting text
    //
    // https://github.com/facebook/react/issues/7253


    function setDefaultValue(node, type, value) {
      if ( // Focused number inputs synchronize on blur. See ChangeEventPlugin.js
      type !== 'number' || node.ownerDocument.activeElement !== node) {
        if (value == null) {
          node.defaultValue = toString(node._wrapperState.initialValue);
        } else if (node.defaultValue !== toString(value)) {
          node.defaultValue = toString(value);
        }
      }
    }