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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With