0

Is there any way to check the position inside the textbox by using javascript, or any kinds of javascript framework? Say, the figure 1 is at position 2 and the figure 3 is at position 3.

enter image description here Figure. 1.

enter image description here Figure. 2.

BLAdam
  • 45
  • 4

2 Answers2

1

Below are the 2 helpful methods:

function doGetCaretPosition (ctrl) {

    var CaretPos = 0;
    // IE Support
    if (document.selection) {

        ctrl.focus ();
        var Sel = document.selection.createRange ();

        Sel.moveStart ('character', -ctrl.value.length);

        CaretPos = Sel.text.length;
    }
    // Firefox support
    else if (ctrl.selectionStart || ctrl.selectionStart == '0')
        CaretPos = ctrl.selectionStart;

    return (CaretPos);

}


function setCaretPosition(ctrl, pos)
{

    if(ctrl.setSelectionRange)
    {
        ctrl.focus();
        ctrl.setSelectionRange(pos,pos);
    }
    else if (ctrl.createTextRange) {
        var range = ctrl.createTextRange();
        range.collapse(true);
        range.moveEnd('character', pos);
        range.moveStart('character', pos);
        range.select();
    }
}
Chankey Pathak
  • 21,187
  • 12
  • 85
  • 133
0

You can use Jquery Caret plugin.

pos = $(textarea).caret()

jQuery Caret

Gubi
  • 415
  • 2
  • 10
  • 20