Skip to content

Instantly share code, notes, and snippets.

@bvarga
Created August 5, 2013 12:00
Show Gist options
  • Save bvarga/6155414 to your computer and use it in GitHub Desktop.
Save bvarga/6155414 to your computer and use it in GitHub Desktop.
insert text at a given position
insertAtCursor: function(myField, myValue) {
//IE support
if (document.selection) {
myField.focus();
sel = document.selection.createRange();
sel.text = myValue;
}
//MOZILLA/NETSCAPE support
else if (myField.selectionStart || myField.selectionStart == '0') {
var startPos = myField.selectionStart;
var endPos = myField.selectionEnd;
if (myValue == 'backspace') {
myValue ='';
if ( startPos > 0 )
startPos -= 1;
} else
if (myValue == 'del') {
myValue ='';
endPos += 1;
} else
if (myValue == 'up') {
myField.selectionStart = 0;
myField.selectionEnd = myField.selectionStart;
return false;
} else
if (myValue == 'down') {
myField.selectionStart = myField.value.length;
myField.selectionEnd = myField.selectionStart;
return false;
} else
if (myValue == 'left') {
myField.selectionStart = startPos - 1;
myField.selectionEnd = myField.selectionStart;
return false;
} else
if (myValue == 'right') {
myField.selectionStart = startPos + 1;
myField.selectionEnd = myField.selectionStart;
return false;
}
myField.value = myField.value.substring(0, startPos)
+ myValue
+ myField.value.substring(endPos, myField.value.length);
myField.selectionStart = startPos + myValue.length;
myField.selectionEnd = myField.selectionStart;
return true;
} else {
myField.value += myValue;
return true;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment