简体   繁体   中英

Insert Text Into Textarea Where Cursor Is

I have the following JS that inserts some content into a textarea at the end of whatever is in the textarea currently. This all works fine with the following code:

<script>
if (opener.document.post.sMessage.createTextRange && opener.document.post.sMessage.caretPos) {
  var caretPos = opener.document.post.sMessage.caretPos;
  caretPos.text = '\n\n![](http://example.com/image.png)';
} else {
opener.document.post.sMessage.value += '\n\n![](http://example.com/image.png)';
}
self.close(); //close popup
</script>

How can this be modified to insert the content into the textarea where the cursor was in the textarea (instead of just at the end of the existing text)?

Solution with VanillaJS

 function addContentAtCursorFunc( elem, newContent ) { if (elem.selectionStart || elem.selectionStart == '0') { let _startSelection = elem.selectionStart; let _endSelection = elem.selectionEnd; elem.value = elem.value.substring(0, _startSelection) + newContent + elem.value.substring(endPos, elem.value.length); } else { elem.value += newContent; } } const button = document.getElementById('myBtn'); const textarea = document.getElementById('myTextarea'); button.addEventListener('click', event => { addContentAtCursorFunc( textarea , " *| I'M NEW CONTENT! |* ") return false });
 <textarea id="myTextarea" cols="40" rows="3">Select some of this text and then hit the button.</textarea> <button id="myBtn">Type some stuff</button>

Don't have enough reputation to comment, but @GMKHussain's answer contains a typo, I believe.

I think in the line + elem.value.substring(endPos, elem.value.length); endPos should be replaced with _endSelection : + elem.value.substring(_endSelection, elem.value.length);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM