home projects speaker

how to use javascript to insert text at cursor position in a form input element

Note

Please note that this is an archived post, so links, code and the communicated message might be outdated. YMMV

Was stuck in a rut here with a JavaScript problem, but I did some active research that I became very happy with:

    function InsertTextAtCursor(input, valueString){
   //IE support
   if (document.selection) {
      $(input).focus();
      sel = document.selection.createRange();
      sel.text = valueString;
    }
    //MOZILLA/NETSCAPE support
   else if ($(input).selectionStart || $(input).selectionStart == '0') {
      var startPos = $(input).selectionStart;
      var endPos = $(input).selectionEnd;
      $(input).value = $(input).value.substring(0, startPos)
     + valueString
      + $(input).value.substring(endPos, $(input).value.length);
   } 
   else{
      $(input).value += valueString;
   }

 }

Notice that I've used prototype as well in this solution. The function could be a lot more, but I just need it for one feature only.


About the author

Hi! My name is Alexander, and I am a creative frontender, specializing in UX, accessibility, universal design, frontend-architecture, node and design systems. I am passionate with open source projects and love to dabble with new emerging technologies related to frontend. With over 24 years of frontend experience, I have earned the right to be called a veteran. I am a lover of life, technologist at heart. If I am not coding, I am cooking and I love whisky and cigars. Oh, and coffee, I LOVE coffee!

If you want to know more about me, here is some links you might want to check out: GitHub, Instagram, Twitter, LinkedIn, CodePen, Slides.com, npm,

Speaker

I am also an avid speaker on several topics! Check out some of the things I speak about, and contact me if you are interested in having me at your next event!