0

How to get cursor position in textarea/textbox by using javascript?

I already used document.selection.createrange().I am using IE11.It is throwing an error when I am putting break point.It says 'Undefined'.I already used document.getSelection().I will apreciate if anybody provide me entire code along with explaination

Jui Test
  • 2,399
  • 14
  • 49
  • 76
  • possible duplicate of [Set cursor position in html textbox](http://stackoverflow.com/questions/512528/set-cursor-position-in-html-textbox) – Ramesh Rajendran Mar 11 '15 at 05:19
  • Another duplicate: http://stackoverflow.com/questions/4517198/how-to-get-mouse-position-in-jquery-without-mouse-events – jaumetet Mar 11 '15 at 05:27

1 Answers1

0

My requirement was to paste a value on cursor position in text area and i have done it like this. see if this helps you.

 var txtfield = document.getElementById('myTextfield');
    var val = "myvalues";
    if (document.selection) {           
        sel = document.selection.createRange();
        sel.text = val;
    }
    else if (txtfield.selectionStart || txtfield.selectionStart == '0') {
        var startPos = txtfield.selectionStart;
        var endPos = txtfield.selectionEnd;
        txtfield.value = txtfield.value.substring(0, startPos) + val + txtfield.value.substring(endPos, txtfield.value.length);
    }
Irfan TahirKheli
  • 3,652
  • 1
  • 22
  • 36