views:

391

answers:

3

I'm looking for a way to set a selection in a textarea in Internet Explorer. In other browsers, this works just fine:

textarea.selectionStart = start;
textarea.selectionEnd = end;

In IE, I assume I have to use createRange and adjust the selection somehow, but I cannot figure out how.

Extra bonus points for a link to a proper documentation about createRange and associated methods, MSDN isn't helping out much.

+3  A: 

This works for me:

<textarea id="lol">
noasdfkvbsdobfbgvobosdobfbgoasopdobfgbooaodfgh
</textarea>

<script>
var range = document.getElementById('lol').createTextRange();
range.collapse(true);
range.moveStart('character', 5);
range.moveEnd('character', 10);
range.select();
</script>

Useful links:

moveStart() at MSDN: http://msdn.microsoft.com/en-us/library/ms536623%28VS.85%29.aspx

moveEnd() at MSDN: http://msdn.microsoft.com/en-us/library/ms536620%28VS.85%29.aspx

watain
Excellent, it actually works. `moveEnd` apparently moves the selection relative to the start position, so it behaves differently than `.selectionEnd`. Great links, thanks! Hopefully the bonus points I promised will come through other people upvoting :)
Tatu Ulmanen
+3  A: 

Try with

function select(e, start, end){
     e.focus();
     if(e.setSelectionRange)
        e.setSelectionRange(start, end);
     else if(e.createTextRange) {
        e = e.createTextRange();
        e.collapse(true);
        e.moveEnd('character', end);
        e.moveStart('character', start);
        e.select();
     }
}
select(document.getElementById('textarea_id'), 5, 10);
Rafael
+1 for creating a browser-aware function and moving the end first so no arithmetic isn't required. It's a shame I can't accept two answers as correct, watain was first and provided links :)
Tatu Ulmanen
Thank you. I know, watain was first and provided some links to documentation, so his answer is the one to be marked as accepted.
Rafael
A: 

Beware of line separators, move* methods see them as one character, but they are actually two - \r\n

johan yong