简体   繁体   中英

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.

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();  

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM