Search code examples
jquerytextareainline-editing

How can I modify dynamically injected code in a textarea?


I have an empty textarea .

<textarea id="final-code"></textarea>

In a js file, I have blocks of code that I put in variables :

var big_block='...'
var medium_block='...'
etc.

Then I create buttons so that the user can generate his code

$('#bigBlock').on('click',function(){
    textarea.text(big_block);
  });
$('#mediumBLock').on('click',function(){
   textarea.text(medium_block)
});

Now I add a text field and a select field. In the code injected into the textarea, there are several links with parameters. what I'm looking to do is modify these parameters through the text fields and the select field. I would like my change to be done live, so that in the end the user can copy the code. The link looks like :

google.com?P1=xx&R=x&name=Myname&job=Myjob 

First I wrapped the text inside span with class, but if I simply do :

$(".myinputtext").on('input', function () {
            var newtext =  $(this).val();
            $(".oldtext").html(newtext );
          });

It doesn't work. And that would not remove the span tag from the code, which is not suitable.

what I'm missing is the syntax to loop over all the words "Myname" and "Myjob" present in the textarea and replace them on the fly with the input and the select field.

if I do something like :

 var textarea = $("#textarea");
  $(".myNexText").on('input', function () {
        var o =  $(this).val();
        textarea.html(textarea.html().replace(/Myname/g, o)); 
    });

it only takes the first letter of what I type..why?


Solution

  • Finaly I found a solution. Instead of trying to target a class, I target a string. And instead of trying with .on('input'), I added a button and did it with .on ('click') :

      var textarea = $("#mytextarea");
      $("#mybutton").on('click', function () {
       var o =  $('.myinput').val();
       textarea.html(textarea.html().replace(/Word/g, o)); 
      });
    

    This allows me to delete all occurrences of the word "Word" and replace it on click with the user's text And for the select field,

    $('.myselect').on('change' , function() {
      code = $(this).val();  //the value
      text = $('.myselect option:selected').html();  //the text
      textarea.html(textarea.html().replace(/Myname/g,code));
      textarea.html(textarea.html().replace(/Myjob/g,text));
      });
    

    I didn't find a way to make it works with on('input') which seems more user friendly to me...if ever someone have a solution ?