user3492770
user3492770

Reputation: 11

Search and replace word of textarea onclick

I'm looking for a way to search and replace some word onclick (not all content). It's working only on predefined textarea. I want to run the script for the words I've just wrote.

<form action="#">
<textarea class="input" name="input" type="text" id="txt" />test</textarea>
<input type="button" value="Run" id="run"/>
</form>

$(document).ready(function() {
    $('#run').click(function() {
    var textarea=$('#txt'); 
    textarea.html(textarea.html().replace(/test/g,"ok")); 
    });
});

Upvotes: 1

Views: 2471

Answers (3)

bumbumpaw
bumbumpaw

Reputation: 2530

FIDDLE HERE

  textarea.val(textarea.val().replace(/test/g,"ok"));

html()

Obtains the HTML content of the first element in the matched set.

val()

Returns the value attribute of the first element in the matched set. When the element is a multiselect element, the returned value is an array of all selections. This method only work with control like input, select, button etc. It not work with div, span, p etc.

Difference of .val() and .html() link here

Upvotes: 0

Ra&#250;l Monge
Ra&#250;l Monge

Reputation: 223

$(document).ready(function() {
    $('#run').click(function() {
    var textarea=$('#txt'); 
    textarea.val(textarea.val().replace(/test/g,"ok")); 
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<textarea class="input" name="input" type="text" id="txt" />test</textarea>
<input type="button" value="Run" id="run"/>

Upvotes: 2

albert Jegani
albert Jegani

Reputation: 462

$('#run').click(function() {
    var textarea=$('#txt'); 
    textarea.val(textarea.val().replace(/test/g,"ok")); 
    });

Upvotes: 1

Related Questions