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.<
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.