Tuesday, October 8, 2013

Inserting text after cursor position in text areа

$.fn.extend({
                   insertAtCaret: function (myValue) {
                        if (!this.selectionStart)
                            thi = $(this).get(0);
                        if (thi.selectionStart || thi.selectionStart == '0') {
                            var startPos = thi.selectionStart;
                            var endPos = thi.selectionEnd;
                            var scrollTop = thi.scrollTop;
                            thi.value = thi.value.substring(0, startPos) + myValue + thi.value.substring(endPos, thi.value.length);
                            thi.focus();
                            thi.selectionStart = startPos + myValue.length;
                            thi.selectionEnd = startPos + myValue.length;
                            thi.scrollTop = scrollTop;
                        } else {
                            thi.value += myValue;
                            thi.focus();
                        }
                    }
                })

Convert jQuery object to DOM object

jQuery Object
$('textarea')
example of setting a value
$('textarea').val("Hi");
DOM object
$('textarea').get(0)
example of setting a value
$('textarea').get(0).value = "Hi";