简体   繁体   中英

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?

HTML looks like this -

    <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();

Thanks

store the string to replace in 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/

UPDATE:

I find the previous example its not safe, Because it replaces all Match char's in Entire area. 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/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM