Michael Joseph Aubry
Michael Joseph Aubry

Reputation: 13462

Append HTML to text-area while keeping the existing text-area content, and appending to where the cursor is?

The question sounds long but I am looking for a real simple basic solution.

HTML:

    <textarea id="test">Hello world</textarea>

                  <a>change</a>

jQuery:

    $('a').click(function() {

        var htmlString = '<div class="football"></div>'
        var existing = jQuery('#test').text()

        $('#test').append().text(existing + htmlString).html();

    });

This appends the existing text with my htmlString variable, for one is this how I should add htmlString into the text-area while keeping the existing content, or is there a better way?

Also its important to me to append htmlString where the cursor is, it makes more sense in my live code, but you should get the idea, this kind of defeats my code above stringing both of those variables like that. So I am open to some ideas :)

Here is a fiddle for you to get a better visual of what that code does FIDDLE

Upvotes: 2

Views: 1152

Answers (1)

Updated Demo

(function ($) {
    $.fn.getCursorPosition = function () {
        var input = this.get(0);
        if (!input) return; // No (input) element found
        if ('selectionStart' in input) {
            // Standard-compliant browsers
            return input.selectionStart;
        } else if (document.selection) {
            // IE
            input.focus();
            var sel = document.selection.createRange();
            var selLen = document.selection.createRange().text.length;
            sel.moveStart('character', -input.value.length);
            return sel.text.length - selLen;
        }
    }
})(jQuery);

$('a').click(function () {
    var htmlString = '<div class="football"></div>';
    var txt = $('#test').text();
    var cur_pos = $('#test').getCursorPosition();
    if (cur_pos != 0) {
        $('#test').val(txt.substring(0, cur_pos) + htmlString + txt.substring(cur_pos + 1));
    }else{
        $('#test').val(htmlString + txt);
    }
});

Upvotes: 3

Related Questions