JavaScript/jQuery - replace text in input text

2019-08-01 09:37发布

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

5条回答
Juvenile、少年°
2楼-- · 2019-08-01 09:45

If you want to clear it when you type and return its text when going away use this

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

$('#id0').blur(function() {$(this).val('  Your text    '); });  
查看更多
老娘就宠你
3楼-- · 2019-08-01 09:46
$('#id0').val('somenewtexthere');
查看更多
forever°为你锁心
4楼-- · 2019-08-01 09:46

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

查看更多
乱世女痞
5楼-- · 2019-08-01 09:48

Most browsers support selectionStart and selectionEnd properties 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:

$("#id0").replaceSelectedText("SOME NEW TEXT");

If the text box does not have the focus, you'll need to focus it first:

$("#id0").focus();
查看更多
趁早两清
6楼-- · 2019-08-01 10:07

I'm not sure if this helps you but maybe in this way:

  var myMessage="My Text";
  $('#id0').val(myMessage);
查看更多
登录 后发表回答