Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I set the cursor to a particular position in the string value of a text INPUT field in Internet Explorer?

I already have this working in Firefox, Safari and Chrome.

I would like to be able to programmatically set the position of the text cursor within an INPUT field in Internet Explorer.

I looked this topic up on various websites and generally found the same technique:

var el = document.getElementById("myTextField");
var pos = 6;

if (document.selection) {
    el.focus();
    var selection = document.selection.createRange();
    selection.moveStart("character", -el.value.length);
    selection.moveStart("character", pos);
    selection.moveEnd("character", 0);
    selection.select();
}

The problem is that when I try to do this the cursor always goes to the end of the value regardless of what position I provide.

Did I misunderstand the technique people have been using? Did I miss something somewhere? It's a little bit frustrating, but of course that's the nature of web development with these different browsers.

Thanks in advance for any help.

like image 552
natlee75 Avatar asked Jul 25 '11 21:07

natlee75


1 Answers

The following code is working for me in IE 9

<script type="text/javascript">
    var input = document.getElementById("myInput");
    input.selectionStart = 2;
    input.selectionEnd = 5;
</script>

Here is the code that I'm using for IE 6

      input.select();
        var sel = document.selection.createRange();
        sel.collapse();
        sel.moveStart('character', this.SelectionStart);
        sel.collapse();
        sel.moveEnd('character', this.SelectionEnd - this.SelectionStart);
        sel.select();  
like image 167
BALKANGraph Avatar answered Sep 22 '22 17:09

BALKANGraph