0

Edit to add: I first asked about a textarea - I had a feeling it just wasn't possible with a textarea by its nature. Could I do this with a contenteditable div?

Within a contenteditable div, when the user enters %TEST% I would like to add a span with a class around %TEST% to be able to add styling to it.

It runs if %TEST% is in the html, but I need it to run if %TEST% is typed in by the user.

<div contenteditable="true" class="myEntry">We're happy you're here, %TEST%. Let's get started.</div>

using jquery I have:

$('.myEntry).each(function () {
    var original = $(this).text();
    var new_version = original.split('%TEST%').join('<span class="stylizeMe">Test</span>');
    $(this).html(new_version)
});
mdhttr248
  • 5
  • 1
  • 3

2 Answers2

2

this can't be done with textarea Element

try to simulate textarea element with another element like div or span or pre

1

The content model for textarea is processed character data therefore element inside textarea will not accepted. However you can use content editable div as alternative solution.

<div id="editable" contenteditable="true"></div>

Then you can use jQuery to update %TEXT% -> <span class='myTest'>%TEST%</span>, if you want to use Javascript you need to use input event beacuse onchange does not support for contenteditable

$('body').on('blur', '[contenteditable]', function() {
   $(this).html(function () {
    return $(this).text().replace(/%TEST%/g, "<span class='myTest'>%TEST%</span>"); 
  });
});

However contenteditable does not work as a form element therefore you have to use Javascript or jQuery to apply contenteditable in your work.

<script>
        document.getElementById("textarea").value = document.getElementById("content").innerHTML;
</script>

<div id="content" contenteditable="true">Text</div>

<form>
    <textarea id="textarea" style="display:none"></textarea>
</form>

Workable sample: https://jsbin.com/zuyemabiwo/1/edit?html,css,js,console,output

Casper
  • 1,469
  • 10
  • 19
  • Yes this is so close! But, if %TEST% is entered by the user more than once, it only applies the span to the most recent entry – mdhttr248 Sep 20 '19 at 03:48