Inserting a text where cursor is using Javascript/jquery

前端 未结 13 2675
盖世英雄少女心
盖世英雄少女心 2020-11-22 03:58

I have a page with a lot of textboxes. When someone clicks a link, i want a word or two to be inserted where the cursor is, or appended to the textbox which has the focus.<

13条回答
  •  后悔当初
    2020-11-22 04:33

    Maybe a shorter version, would be easier to understand?

        jQuery("#btn").on('click', function() {
            var $txt = jQuery("#txt");
            var caretPos = $txt[0].selectionStart;
            var textAreaTxt = $txt.val();
            var txtToAdd = "stuff";
            $txt.val(textAreaTxt.substring(0, caretPos) + txtToAdd + textAreaTxt.substring(caretPos) );
        });
    
    
    
    

    I wrote this in response to How to add a text to a textbox from the current position of the pointer with jquery?

提交回复
热议问题