English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Simple Example of Inserting Content at a Specified Position in Text with JS

Example as follows:

function insertAtCursor(myField, myValue) { 
 //Internet Explorer browser 
 if (document.selection) { 
  myField.focus(); 
  sel = document.selection.createRange(); 
  sel.text = myValue; 
  sel.select(); 
 } 
 //Firefox, Chrome, and others 
 else if (myField.selectionStart || myField.selectionStart == '0') { 
  var startPos = myField.selectionStart; 
  var endPos = myField.selectionEnd; 
  // Save scrollbar 
  var restoreTop = myField.scrollTop; 
  myField.value = myField.value.substring(0, startPos)} + myValue + myField.value.substring(endPos, myField.value.length); 
  if (restoreTop > 0) { 
  myField.scrollTop = restoreTop; 
  } 
  myField.focus(); 
  myField.selectionStart = startPos + myValue.length; 
  myField.selectionEnd = startPos + myValue.length; 
 } else { 
  myField.value += myValue; 
  myField.focus(); 
 } 
} 
<textarea id="textarea" style="width: 386px; height: 260px"> 
</textarea> 
<input type="text" id="text" /> 
<input type="button" value="Insert" onclick="insertAtCursor(document.getElementById('textarea'),document.getElementById('text').value)" /> 

This simple example of JS implementation for inserting content at a specified position in the text is all the editor shares with you. I hope it can provide a reference for everyone, and I also hope everyone will support the Shouting Tutorial.

Declaration: The content of this article is from the network, and the copyright belongs to the original author. The content is contributed and uploaded by Internet users spontaneously. This website does not own the copyright, has not been manually edited, and does not assume any relevant legal responsibility. If you find any content suspected of copyright infringement, please send an email to: notice#w3Please report violations by replacing # with @ in the email, and provide relevant evidence. Once verified, this site will immediately delete the infringing content.

You May Also Like