6

I would like to get the position of the cursor in an <input>. Here is the code that I am using:

$("input").keyup(function() {
    $("<p>")
    .html("Cursor position at " + $("input").caretPosition())
    .appendTo("#test");
});

And caretPosition is defined as (just a wrapper for selectionStart):

$.fn.caretPosition = function() {
    if (!this.length) return;
    var input = this[0];
    try {
      return input.selectionStart;
    } catch(e) {
      // No need for old IE support
      return 0;
    }
}

HTML

<input type="number" />
<div id="test">
</div>

Unfortunately this isn't working in chrome, but it is working if Firefox. In chrome, it prints 0 all the time. This would make me think that chrome doesn't support selectionStart but I have read that it does support selectionStart. This is supported by the fact that if I change type="number" to type="text" it starts working. How do I get it to work consistently across browsers for type="number"? (not IE, don't need support for that).

I have read https://stackoverflow.com/a/2897510/3371119 but it doesn't work for me (in chrome).

Jsfiddle: http://jsfiddle.net/prankol57/zbaaky5z/2/

Edit: I have confirmed that selectionStart in input returns true. So why is an error thrown?

2
  • Only a few input types support selectionStart according to the standard. whatwg.org/specs/web-apps/current-work/multipage/… Why do you want to get the caret position? Commented Aug 18, 2014 at 15:03
  • @int32_t Good point. Thanks. I just realized that when I checked the console error message if I remove the try {} catch statement. Commented Aug 18, 2014 at 20:37

1 Answer 1

6

As @int32_t pointed out, this is impossible with <input type="number" />. I changed it to <input type="text" /> and was able to receive this functionality; I added my own number-validating method like so:

function validate(k) {
  return !isNaN(parseFloat(k)) && !isNaN(+k);
}

In fact, if you remove the try {} catch {} statements, chrome throws a very descriptive error:

Uncaught InvalidStateError: Failed to read the 'selectionStart' property from
'HTMLInputElement': The input element's type ('number') does not support
selection.
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.