Inserting a text where cursor is using Javascript/jquery

前端 未结 13 2646
盖世英雄少女心
盖世英雄少女心 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:36

    This question's answer was posted so long ago and I stumbled upon it via a Google search. HTML5 provides the HTMLInputElement API that includes the setRangeText() method, which replaces a range of text in an <input> or <textarea> element with a new string:

    element.setRangeText('abc');
    

    The above would replace the selection made inside element with abc. You can also specify which part of the input value to replace:

    element.setRangeText('abc', 3, 5);
    

    The above would replace the 4th till 6th characters of the input value with abc. You can also specify how the selection should be set after the text has been replaced by providing one of the following strings as the 4th parameter:

    • 'preserve' attempts to preserve the selection. This is the default.
    • 'select' selects the newly inserted text.
    • 'start' moves the selection to just before the inserted text.
    • 'end' moves the selection to just after the inserted text.

    Browser compatibility

    The MDN page for setRangeText doesn't provide browser compatibility data, but I guess it'd be the same as HTMLInputElement.setSelectionRange(), which is basically all modern browsers, IE 9 and above, Edge 12 and above.

    0 讨论(0)
提交回复
热议问题