JavaScript / jQuery - replace text in input text
Let's say we have an input field: <input type="text" id="id0"/> . I would like to dynamically replace the current text of text with text. What is the best way to achieve this using jQuery or javascript?
Update:
I meant: the user enters the text and selects part of it, then presses the button to replace the selected section with the other specified text.
Regards, Rafal
Most browsers support the selectionStart and selectionEnd properties for text fields and text fields. However, IE <9 is not. You can use my Rangy plug-in for this, which normalizes IE <9 clutter lack of support and provides convenient methods for handling selections in text inputs and text areas. Using it, the code will look like this:
$("#id0").replaceSelectedText("SOME NEW TEXT"); If the text field has no focus, you first need to focus it:
$("#id0").focus();