Let’s say we have an input field: <input type="text" id="id0"/>. I would like to dynamically replace the current selection of the text with my text. What is the best way to achieve that using jQuery or javascript?
Update:
I meant: the user types the text and selects part of it, then presses a button to replace the selected section with another specified text.
Regards, Rafal
Most browsers support
selectionStartandselectionEndproperties on text inputs and textareas. However, IE < 9 does not. You could use my Rangy inputs plug-in for this, which normalizes the mess of IE < 9’s lack of support and provides convenient methods for dealing with selections in text inputs and textareas. Using it, the code would be:If the text box does not have the focus, you’ll need to focus it first: