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?
try {} catchstatement.