[英]How do I replace a specific piece of text in a textarea on a keyup event that gets the value of another input box
How do I replace a specific piece of text in a textarea on a keyup event that gets the value of another input box and replaces the specific piece of text in the textarea? 如何在获取另一个输入框的值并替换文本区域中特定文本的keyup事件上替换文本区域中特定文本的文本?
HTML looks like this - HTML看起来像这样-
<div>
<label>test1</label>
<input name="test_1" id="test1" type="text">
<label>Message</label>
<textarea rows="2" name="textarea_2" id="textarea2">Hello [initial text] blah blah blah</textarea>
</div>
I want to replace [initial text] with whatever is put into $('#test1').val(); 我想用$('#test1')。val();中的任何内容替换[初始文本];
Thanks 谢谢
store the string to replace in var: 将要替换的字符串存储在var中:
var lastStr = "[initial text]";
$("#test1").keyup(function() {
var val = $("textarea").val();
$("textarea").val(val.replace(lastStr, $("#test1").val()));
lastStr = $("#test1").val(); // update last str to replace.
});
demo: http://jsfiddle.net/k9uG4/1/ 演示: http : //jsfiddle.net/k9uG4/1/
UPDATE: 更新:
I find the previous example its not safe, Because it replaces all Match char's in Entire area. 我发现前面的示例并不安全,因为它替换了整个区域中的所有Match char。 this example Replaces only the specific piece we want:
本示例仅替换我们想要的特定部分:
var lastStr = "[initial text]";
var startIndex = $("textarea").val().indexOf(lastStr);
$("#test1").keyup(function() {
var oldVal = $("textarea").val();
// get all the text before
var firstPart = oldVal.substring(0, startIndex);
// get the piece we want And replace it
var midPart = oldVal.substr(startIndex, lastStr.length).replace(lastStr, $("#test1").val());
// get all the text after
var lastPart = oldVal.substring(startIndex + lastStr.length, oldVal.length);
$("textarea").val( firstPart + midPart +lastPart );
lastStr = $("#test1").val();
});
demo: http://jsfiddle.net/k9uG4/6/ 演示: http : //jsfiddle.net/k9uG4/6/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.