IE textarea selectionStart is invalid after setting a value containing a new line

If I type a, and then <enter>into the IE11 text area and the log selectionStart, it 2(this is what I would expect). However, if I put the textarea value programmatically on 'a\n', it selectionStartwill be instead 4.

$('textarea').val('a\n');
console.log($('textarea').get(0).selectionStart);

Anyway, to get the exact cursor position here?

+3
source share
1 answer

This is due to the fact that in IE the cursor does not move if the text field was not focused at first.

Try

$('textarea').focus().val('a\n');
console.log($('textarea').get(0).selectionStart);
0
source

All Articles