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

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

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

I looked at this topic on different sites 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 no matter what position I provide.

I misunderstood what technique people used? Did I miss something? This is a little disappointing, but, of course, the nature of web development with these different browsers.

Thanks in advance for your help.

+4
source share
1 answer

The following code works 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 I use 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(); 
+4
source

All Articles