Subscribe - It's FREE!!

Stay Connected Here

Stay Updated With Us Here



Google

How to insert text at cursor position using jQuery


Share with WhatsApp


In this post I am sharing how you can insert text at cursor postion in focused textbox or textarea.

I have used the function provided by Eli(http://stackoverflow.com/users/1479606/eli) in one of the stackoverflow answer, so all credit goes to her. In this function text gets inserted at cursor position but to handle multiple textarea or I haved some more code which I am going to share here.

The core logic to insert text is reside in te above function only but to handle multiple textarea's we need to consider handling focus event and track currently focused textarea only.

Below is the HTML code

<textarea class="inputHolder" cols="30" rows="10"></textarea>
<textarea class="inputHolder" cols="30" rows="10"></textarea>
<input type="text" id="txtInput"  />
<br/>
<br/>
<button id="test">Insert "Test" at Cursor position</button>

I have used a class below class to identify which input is currently focused, for demo purpose I have added a border.

.insertatcaretactive
{
border:1px soild #1e90ff;
}

Now actual JS code which handles this functionality

$.fn.EnableInsertAtCaret = function() {
$(this).on("focus", function() {        $(".insertatcaretactive").removeClass("insertatcaretactive");
     $(this).addClass("insertatcaretactive");
});
};


function InsertAtCaret(myValue) {

    return $(".insertatcaretactive").each(function(i) {
        if (document.selection) {
            //For browsers like Internet Explorer
            this.focus();
            sel = document.selection.createRange();
            sel.text = myValue;
            this.focus();
        } else if (this.selectionStart || this.selectionStart == '0') {
            //For browsers like Firefox and Webkit based
            var startPos = this.selectionStart;
            var endPos = this.selectionEnd;
            var scrollTop = this.scrollTop;
            this.value = this.value.substring(0, startPos) + myValue + this.value.substring(endPos, this.value.length);
            this.focus();
            this.selectionStart = startPos + myValue.length;
            this.selectionEnd = startPos + myValue.length;
            this.scrollTop = scrollTop;
        } else {
            this.value += myValue;
            this.focus();
        }
    })
}

And now implementation of the above js code.

$(".inputHolder,#txtInput").EnableInsertAtCaret();

$('#test').click(function() {
    InsertAtCaret('test');
});

In above code, just to show how you can use multiple selectors, I have used one input with id and two textarea's with a class name but you can use single class for all input too.

Below is the live fiddle of the same code.

Hope you have benefited from this post. This code can be optimized in more better way so if you have an alternative or something positive to add this post. Do share it in comment section. Thanks.



If you enjoyed this post take 5 seconds to share it! Be Socialable. :-)

Share with WhatsApp

Posts To Read Next

Typewriter - Automatic TypeScript Template generation from C# classes in Visual Studio

Typewriter, an extension for visual studio that generates TypeScript files from C# code files using TypeScript templates. Convert your C# model classes to TypeScript automatically.


Swagger - Powerful Opensource Framework for RESTful API

With a Swagger-enabled API, you get interactive documentation, client SDK generation and discoverability. Swagger Editor allows you to generate code, documentation with ease.


Visual Studio Code - Lighweight but powerful source code editor available for Windows, OS X and Linux

Visual Studio Code is a lightweight but powerful source code editor which runs on your desktop and is available for Windows, OS X and Linux. It comes with built-in support for JavaScript, TypeScript and Node.js and has a rich ecosystem of extensions for other languages (C++, C#, Python, PHP) and runtimes.


Assembla - Free and private repository to manage your source code online with SVN subversion hosting

With Assembla you can share source code with others online. Free & Private source code repository with SVN Subversion, Git & Perforce Hosting.


How to call click or any event only once in jQuery

Know how to execute an click event or any event only once for any element in jQuery. Perform action only once and even not required to unbind event.


Your opinion is valuable for us! Comments, suggetions are welcome.


Submit your Email Id to stay updated with us and get notified with our new posts. It's FREE!
Vu 32'' TV Vu 24'' TV
We know this popup is disturbing you!
But We would greatly appreciate if you share us with your friends below!

It will not take more than 2 seconds but will motivate us greatly to write more,share more!

x