maximelian1986
maximelian1986

Reputation: 2472

Getting cursor position in input type number

I trying to get cursor position inside input field, which is type number

<input type="number" id="myInput">

And I tried standard selectionStart property, but apparently it does not work for number fields.

var start = document.getElementById("myInput").selectionStart;

Is there any why or workaround to get that information inside keypress event? My end goal is it prevent leading zeros in such input field, for that I need to know is user input coming to start of existing value.

Currently I stripping those zeros in keyup event:

var inputFieldValue = $(this).val();
$(this).val(removeLeadingZeros(inputFieldValue)); // removeLeadingZeros: inputString.replace(/^0+/, "");

But with that solution those zeros became visible for a second before been removed, that behavior I want to prevent.

Any ideas? How I can get end result string before it provided to user inside input element? Even as selectionStart value not available for number input, browser somehow know where to put those new characters, so there must be some way to capture that and may be prevent some default behavior or stop bubbling.

Upvotes: 0

Views: 550

Answers (1)

kiran raj
kiran raj

Reputation: 26

You can try RegExp

<input type="number" id="myInput">

$("#myInput").on("input", function() {
  if (/^0/.test(this.value)) {
    this.value = this.value.replace(/^0/, "")
  }
});

Upvotes: 0

Related Questions