tobiasg tobiasg - 9 days ago 8
HTML Question

Replace string in textarea on click and then copy (jQuery)

I have this form with a

textarea
and a
button
. If someone enters a text in the textarea and clicks the button, I want the function to search for if "Tobias" was entered in the textarea and if so, replace it with "Hanna" and finally copy it to the clipboard.

If I enter this in the textarea...


Tobias is great!


...and then click the button; I want this to be copied to the clipboard:


Hanna is great!


But it won't work. This is the code so far:

$("button").click(function(){
var $textArea = $("textarea");
var $newText = $textArea.val().replace("Tobias", "Hanna");
$newText.select();
document.execCommand('copy');
});

Answer

You can't do a .select() on a string. As per the documentation, its use is limited to <input type="text"> and <textarea> elements.

Perhaps what you're looking for is something like this: https://jsfiddle.net/6mz4qyL0/3/

$("button").click(function(){
    var $textArea = $("textarea");
    var oldText = $textArea.val();
    var newText = oldText.replace("Tobias","Hanna");
    $textArea.val(newText).select();
    document.execCommand('copy');
    $textArea.val(oldText);
});

This changes the textarea value to the replacement text, copies it, and then changes it back, all without the user knowing.


Additionally as a friendly note... While there is nothing syntactically incorrect with your $newText variable, I'd personally suggest dropping the $ from its name.

When working with a block of jQuery code, those familiar with the language will most likely assume that a variable prefixed with $ refers to a jQuery object/array. In your case, $newText is a basic string, so it's quite deceiving.

Comments