Reputation: 305
I have an html:
<input id="replace"></input>
<div id="replacepls">Go!</div>
<br>
<textarea id="text" name="text"></textarea>
and some js code there:
$('textarea[name=text]').val('Hello my dear friend, i love u');
$('#replacepls').click(function(){
var news = $('#replace').val();
var text = $(this).text();
$(this).text(text.replace('friend', news));
});
How can i replace word "friend" in textarea to other word from input on button click? Why my code does not work? Thank you.
Upvotes: 2
Views: 207
Reputation: 9637
You need to use val()
instead of text()
, and also i simplified your code
$('#replacepls').click(function () {
$("#text").val(function (i, val) {
return val.replace('friend', $('#replace').val())
});
})
Upvotes: 1
Reputation: 148180
You need to use val() instead of text() with textarea
, $(this).text() will give you text of div
with text Go but not the text in the textarea
$('textarea[name=text]').val('Hello my dear friend, i love u');
$('#replacepls').click(function () {
var news = $('#replace').val();
var text = $('#text').val();
$('#text').val(text.replace('friend', news));
});
Upvotes: 2
Reputation: 12024
Replace $(this).text(text.replace('friend', news));
With:
$(this).text($("#text").val().replace('friend', news));
Upvotes: 0