Epi
Epi

Reputation: 322

Is there a way to get caret position of input with type text?

Background

I need to filter all input made in a browser via JavaScript and decided to attach a handler in the capturing phase like this:

window.addEventListener('keypress', keyPressListener, true);

Inside this listener I prevent the default action, do the filtering and eventually trigger a custom event which contains the information on the pressed key. (My initial approach was to trigger the original (prevented) keypress event which should get handled by the default action. I realised that this is not possible because script generated events are not trusted and non trusted events do not invoke the default action in Chrome starting with version 53.)

Problem

If I now try to update an input element with my custom listener I want to consider the current cursor position like this:

var caretPosition = element.selectionStart;
element.val(newVal);
this.setSelectionRange(cursorPosition+1, cursorPosition+1);

This works fine for input elements with type text but not at all for input elements with type number because the number type does not support selection.

Is there any (cross browser compatible) way to set the cursor in an input element with type number or can you point out another solution for this problem?

My keyPressListener looks like this:

    var keyPressListener = function(event) {
           //attach custom handler
            attachInputProcessedListenerTo(event.target);
            event.preventDefault();
        }
    };

With the above code I prevent the default action and attach a custom handler which gets triggered if my filter let pass the input. As you can see, I attach this handler automatically on any element which received a key press.

Upvotes: 2

Views: 540

Answers (1)

SLePort
SLePort

Reputation: 15461

For numbers you could use a text input with a number pattern:

<form>
  <input type="text" pattern="[\d\.]*">
  <button>Submit</button>
</form>

Upvotes: 2

Related Questions