Posted By

brandonjp on 02/02/11


Tagged

javascript js caret cursor position onclick


Versions (?)

JS - onclick function to insert text characters symbol into text input field or textarea at the cursor caret location position


 / Published in: JavaScript
 

// big thanks to these tips for giving me code to steal: http://bit.ly/bundles/brandonjp/9

/* * USAGE: give your HTML textarea or text input element an ID * give your button an onClick="insertThisInThere(text2insert, theInputIDwhereItGoes);" * * EX: * */

  1. // big thanks to these tips for giving me code to steal: http://bit.ly/bundles/brandonjp/9
  2.  
  3. /*
  4.  * USAGE: give your HTML textarea or text input element an ID
  5.  * give your button an onClick="insertThisInThere(text2insert, theInputIDwhereItGoes);"
  6.  *
  7.  * EX: <input type="text" id="myInput" /> <input type="submit" value="insert ® symbol" onClick="insertThisInThere('®', 'myInput');" />
  8.  *
  9.  */
  10.  
  11.  
  12. // my bp-ized version so people won't know I stole it all, but really just so I can understand it better
  13.  
  14. function insertThisInThere(thisChar, thereId) {
  15. function theCursorPosition(ofThisInput) {
  16. // set a fallback cursor location
  17. var theCursorLocation = 0;
  18.  
  19. // find the cursor location via IE method...
  20. if (document.selection) {
  21. ofThisInput.focus();
  22. var theSelectionRange = document.selection.createRange();
  23. theSelectionRange.moveStart('character', -ofThisInput.value.length);
  24. theCursorLocation = theSelectionRange.text.length;
  25. } else if (ofThisInput.selectionStart || ofThisInput.selectionStart == '0') {
  26. // or the FF way
  27. theCursorLocation = ofThisInput.selectionStart;
  28. }
  29. return theCursorLocation;
  30. }
  31.  
  32. // now get ready to place our new character(s)...
  33. var theIdElement = document.getElementById(thereId);
  34. var currentPos = theCursorPosition(theIdElement);
  35. var origValue = theIdElement.value;
  36. var newValue = origValue.substr(0, currentPos) + thisChar + origValue.substr(currentPos);
  37.  
  38. theIdElement.value = newValue;
  39.  
  40. }
  41.  
  42.  
  43.  
  44.  
  45.  
  46.  
  47. /** EXAMPLE HTML:
  48.  
  49. <h2>set your cursor anywhere inside the text field, then click the button to insert text at the cursor location -- each button has an onClick="sendChar2Id('®','toThisId');"</h2>
  50.  
  51. <br/><hr /><br/>
  52.  
  53. <input type="text" id="inputOne" value="inputOne" /><br />
  54. <input type="submit" onClick="insertThisInThere('*A*','inputOne')" value="insert *A* into inputOne" />
  55.  
  56. <br/><hr /><br/>
  57.  
  58.  
  59. <textarea id="inputTwo">inputTwo</textarea><br />
  60. <button onClick="insertThisInThere('*B*','inputTwo');">insert *B* into inputOne</button>
  61.  
  62. **/

Report this snippet  

You need to login to post a comment.