. I would like to dynamically repl...">

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

+1
source share
5 answers

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(); 
+1
source
 $('#id0').val('somenewtexthere'); 
0
source

I'm not sure if this will help you, but perhaps this way:

  var myMessage="My Text"; $('#id0').val(myMessage); 
0
source

If you want to clear it when you enter and return your text when leaving, use this

$('#id0').focus(function() { $(this).val(''); });

 $('#id0').blur(function() {$(this).val(' Your text '); }); 
0
source

jQuery ("input # id0"). attr ("value", "my text");

-3
source

Source: https://habr.com/ru/post/1400239/