I have the following piece of JavaScript for dynamically inserting unicode characters - represented below by the txtToIns variable - into a body of text
elmt.value = elmt.value.substring(0, elmt.selectionStart) + txtToIns + " " + elmt.value.substring(elmt.selectionStart, elmt.selectionEnd) + elmt.value.substring(elmt.selectionEnd, elmt.value.length) + " ";
elmt.focus();
elmt.value = elmt.value.trim();
With the above the cursor is always at the end of the text. Is there any way I can place it directly after txtToIns? And no, txtToIns.focus() won't work
I have the following piece of JavaScript for dynamically inserting unicode characters - represented below by the txtToIns variable - into a body of text
elmt.value = elmt.value.substring(0, elmt.selectionStart) + txtToIns + " " + elmt.value.substring(elmt.selectionStart, elmt.selectionEnd) + elmt.value.substring(elmt.selectionEnd, elmt.value.length) + " ";
elmt.focus();
elmt.value = elmt.value.trim();
With the above the cursor is always at the end of the text. Is there any way I can place it directly after txtToIns? And no, txtToIns.focus() won't work
Share Improve this question edited Nov 21, 2022 at 8:26 sideshowbarker♦ 88.1k29 gold badges215 silver badges211 bronze badges asked Apr 16, 2012 at 19:05 AndyWAndyW 2721 gold badge2 silver badges14 bronze badges2 Answers
Reset to default 10I'm not sure what you're trying to do with the space characters in the textarea value, particularly the final one which will get trimmed off again two lines later, so I've ignored the spaces in my code below. I'm also not sure what you're trying to do with the text that was previously selected (if any), so I'm going to assume you want to overwrite it with the new text.
Bear in mind that this will not work in IE < 9, which does not support selectionStart
, selectionEnd
nor setSelectionRange()
.
Demo: http://jsfiddle.net/timdown/wPfVn/
Code:
var val = elmt.value;
var start = elmt.selectionStart, end = elmt.selectionEnd;
elmt.value = val.slice(0, start) + txtToIns + val.slice(end);
elmt.focus();
var caretPos = start + txtToIns.length;
elmt.setSelectionRange(caretPos, caretPos);
When you change the value, the cursor will move to the end. You will have to manually reset the cursor position after you change its value.
Try this:
var start = elmt.selectionStart,
len = txtToIns.length,
pos = start + len;
elmt.value = elmt.value.substring(0, start) + txtToIns + " " + elmt.value.substring(start) + " ";
elmt.focus();
elmt.value = elmt.value.trim();
elmt.setSelectionRange( pos, pos, 0 );
I also cleaned up some unnecessary logic in the line where you set the value. Hopefully I didn't break anything, but if I did, just revert to your original line.