Posted By

roberocity on 10/10/06


Tagged


Versions (?)

Who likes this?

4 people have marked this snippet as a favorite

shamrog12
rnrleachryan
shachi
vali29


InsertAtCursor


 / Published in: JavaScript
 

  1. function insertAtCursor(myField, myValue) {
  2. //IE support
  3. if (document.selection) {
  4. myField.focus();
  5. sel = document.selection.createRange();
  6. sel.text = myValue;
  7. }
  8. //MOZILLA/NETSCAPE support
  9. else if (myField.selectionStart || myField.selectionStart == '0') {
  10. var startPos = myField.selectionStart;
  11. var endPos = myField.selectionEnd;
  12. myField.value = myField.value.substring(0, startPos)
  13. + myValue
  14. + myField.value.substring(endPos, myField.value.length);
  15. } else {
  16. myField.value += myValue;
  17. }
  18. }
  19.  
  20. // calling the function
  21.  
  22. insertAtCursor(document.formName.fieldName, 'this value');

Report this snippet  

Comments

RSS Icon Subscribe to comments
Posted By: GSharp on February 19, 2010

Very useful, thanks. Found one minor issue, in Firefox 3 the focus is not returned to the field. Here's what I did to focus a place the cursor correctly:

myField.focus(); myField.setSelectionRange(startPos + myValue.length, startPos + myValue.length);

You need to login to post a comment.