Skip to content
Advertisement

Change the value of synced textarea with keyup event in JavaScript

I would like to change ik into b each time but it changes only once. I tried lot of methods to change it dynamically but I couldn’t. Can anyone help?

$(document).ready(function() {
    $("#ta_1").keyup(function(event) {          
        var text1 = $("#ta_1").val();      
        var text2 = text1.replace("ik", "b");      
        $("#ta_2").val(text2);
   });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea id="ta_1"   rows="5" cols="28" ></textarea>
<textarea id="ta_2"   rows="5" cols="28"></textarea>

Advertisement

Answer

There is no replaceAll in javascript, you have to use regular expression with global flag for doing that.

So write your code like below,

var text2 = text1.replace(/ik/g,"b");

And your full code would be,

$(document).ready(function() {
    $("#ta_1").keyup(function(event) {          
        var text = $(this).val().replace(/ik/g,"b");
        $("#ta_2").val(text);
   });
});

DEMO

Advertisement