paste text in textrarea

by Seungrae Lee

HTML

<textarea name="comment" rows="15" cols="40" id="comment">Shot through</textarea>
<input type="text" name="pasted" id="pasted" size="20" />
<br />
<button name="btnInsert" id="btnInsert">Insert</button>
<div id="log"></div>

JavaScript

(function ($) {
    jQuery.fn.extend({
        getSelection: function () {
            if (this.lengh === 0) return -1;
            input = this[0];
            var pos;
            if (input.createTextRange) {
                input.focus();
                var sr = document.selection.createRange().duplicate();
                var br = document.body.createTextRange();
                br.moveToElementText(input);

                var all_len = areaLength(input.value);
                br.setEndPoint("StartToStart", sr);

                var _start = all_len - areaLength(br.text);
                var _end = _start + sr.text.length;
                pos = {
                    start: _start,
                    end: _end
                };
            } else if (typeof (input.selectionStart) != "undefined") {
                pos = {
                    start: input.selectionStart,
                    end: input.selectionEnd
                };
            }
            return pos;
        },
        setSelection: function (selectionStart, selectionEnd) {
            if (this.lengh === 0) return this;
            input = this[0];
            if (input.createTextRange) {
                var range = input.createTextRange();
                range.collapse(true);
                range.moveEnd('character', selectionEnd);
                range.moveStart('character', selectionStart);
                range.select();
            } else if (input.setSelectionRange) {
                input.focus();
                input.setSelectionRange(selectionStart, selectionEnd);
            }
            return this;
        }
    });
    // IEの改行コードによる差異を吸収
    function areaLength(value) {
        var ary = value.match(/(\r\n|\n|\r)/gm);
        if (ary) {
            return value.length - ary.length;
        } else {
            return value.length;
        }
    }
})(jQuery);

function console(txt) {
    var log = $("#log").html();
    if (log) log += "<br>"
    $("#log").html(log +...