jQuery implements the method of inserting characters or expressions at the location specified by textarea

  • 2020-05-12 02:14:10
  • OfStack

This article demonstrates an example of how jQuery implements the insertion of characters or expressions at the specified location of textarea. Share with you for your reference. The specific implementation method is as follows:

1. Function definition

(function($){
    $.fn.extend({
        insertAtCaret: function(myValue){
            var $t=$(this)[0];
            if (document.selection) {
                this.focus();
                sel = document.selection.createRange();
                sel.text = myValue;
                this.focus();
            }
            else
                if ($t.selectionStart || $t.selectionStart == '0') {
                    var startPos = $t.selectionStart;
                    var endPos = $t.selectionEnd;
                    var scrollTop = $t.scrollTop;
                    $t.value = $t.value.substring(0, startPos) + myValue + $t.value.substring(endPos, $t.value.length);
                    this.focus();
                    $t.selectionStart = startPos + myValue.length;
                    $t.selectionEnd = startPos + myValue.length;
                    $t.scrollTop = scrollTop;
                }
                else {
                    this.value += myValue;
                    this.focus();
                }
        }
    }) 
})(jQuery);

2. Call the method
$("#textareaId").insertAtCaret(" The new look ");

I hope this article is helpful for you to design jQuery program.


Related articles: