Get current cursor position in a textbox

It looks OK apart from the space in your ID attribute, which is not valid, and the fact that you’re replacing the value of your input before checking the selection.

function textbox()
{
        var ctl = document.getElementById('Javascript_example');
        var startPos = ctl.selectionStart;
        var endPos = ctl.selectionEnd;
        alert(startPos + ", " + endPos);
}
<input id="Javascript_example" name="one" type="text" value="Javascript example" onclick="textbox()">

Also, if you’re supporting IE <= 8 you need to be aware that those browsers do not support selectionStart and selectionEnd.

Leave a Comment