Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inserting text after cursor position in text area

The script below inserts text to the end of text area. I need to change to insert text after current cursor position in the text area.

jQuery(document).ready(function($){
    $('#addCommentImage').click(function(){
        var imageLoc = prompt('Enter the Image URL:');
        if ( imageLoc ) {
            $('#comment').val($('#comment').val() + '[img]' + imageLoc + '[/img]');
        }
        return false;
    });
});
like image 858
Captain Comic Avatar asked Mar 05 '11 11:03

Captain Comic


People also ask

How do I add text to textarea?

To add text to a textarea, access the value property on the element and set it to its current value plus the text to be appended, e.g. textarea. value += 'Appended text' . The value property can be used to get and set the content of a textarea element.

Which function displays the text at current position?

In computer user interfaces, a cursor is an indicator used to show the current position for user interaction on a computer monitor or other display device that will respond to input from a text input or pointing device.

How can get current cursor position in textbox using jQuery?

Answer: Use the jQuery event. pageX and event. pageY pageX and event. pageY in combination with the jQuery offset() method to get the position of mouse pointer relative to an element.


2 Answers

if the above does not work (it didn't in my case - maybe my configuration is little bit different), here is another solution:

you can use this extension function to get the position:

(function ($, undefined) {
    $.fn.getCursorPosition = function () {
        var el = $(this).get(0);
        var pos = 0;
        if ('selectionStart' in el) {
            pos = el.selectionStart;
        } else if ('selection' in document) {
            el.focus();
            var Sel = document.selection.createRange();
            var SelLength = document.selection.createRange().text.length;
            Sel.moveStart('character', -el.value.length);
            pos = Sel.text.length - SelLength;
        }
        return pos;
    }
})(jQuery);

the usage is : var position = $("#selector").getCursorPosition()

to insert text at the position:

var content = $('#selector').val();
var newContent = content.substr(0, position) + "text to insert" + content.substr(position);
$('#selector').val(newContent);

That's all.

like image 95
d.popov Avatar answered Sep 22 '22 01:09

d.popov


You may checkout this answer. The insertAtCaret jquery plugin seems very nice.

like image 23
Darin Dimitrov Avatar answered Sep 26 '22 01:09

Darin Dimitrov