0

I need to set the cursor position of an input. I can get it to work fine in Chrome, but I'm having trouble with IE. I've found code that works fine in IE9/10, but I can't find anything that works in IE8 and older.

This is what I have for Chrome:

var cursorPosition = 5;
var textArea = $('.the-input-I-Need');
textArea[0].selectionStart = cursorPosition;
textArea[0].selectionEnd = cursorPosition;
//now the cursor would be at the 5th spot in the input

Anyone know a way to do this for IE? I can use jQuery, but no other plugins.

user1652427
  • 697
  • 2
  • 8
  • 21

1 Answers1

2

There's a question regarding getting and setting of the caret position in IE on this question: Get caret position in textarea (IE)

It also references an answer for actually getting the caret position here: How to get the start and end points of selection in text area?

There's a healthy amount of code that's specific to dealing with IE, but it will accomplish what you're trying to do. Note that the getter function returns a selection range, just as the setter can be used to set a selection range. In this case, you'd just call it with startOffset equaling endOffset:

setSelection(el, startOffset, endOffset);

function setSelectionRange(input, selectionStart, selectionEnd) {
  if (input.setSelectionRange) {
    input.focus();
    input.setSelectionRange(selectionStart, selectionStart);
  }
  else if (input.createTextRange) {
    var range = input.createTextRange();
    range.collapse(true);
    range.moveEnd('character', selectionEnd);
    range.moveStart('character', selectionStart);
    range.select();
  }
}
Community
  • 1
  • 1
chrisnik
  • 21
  • 1