Arriba
Arriba

Reputation: 305

find and replace text jquery

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

});

http://jsfiddle.net/j1ksrdcp/

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

Answers (3)

Balachandran
Balachandran

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

})

Fiddle

Upvotes: 1

Adil
Adil

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

Live Demo

$('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

Replace $(this).text(text.replace('friend', news));

With:

 $(this).text($("#text").val().replace('friend', news)); 

Upvotes: 0

Related Questions