Skip to content

Instantly share code, notes, and snippets.

@raspo
Created July 15, 2012 15:24
Show Gist options
  • Save raspo/3117408 to your computer and use it in GitHub Desktop.
Save raspo/3117408 to your computer and use it in GitHub Desktop.
Insert text at cursor position
function insertAtCursor(myField, myValue) {
if(document.selection){
myField.focus();
sel = document.selection.createRange();
sel.text = myValue;
} else if(myField.selectionStart || myField.selectionStart == '0') {
var startPos = myField.selectionStart;
var endPos = myField.selectionEnd;
myField.value = myField.value.substring(0, startPos) + myValue + myField.value.substring(endPos, myField.value.length);
} else {
myField.value += myValue;
}
}
insertAtCursor(document.getElementById('myFieldId'), 'test');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment