I am trying to get a textbox to change text in a div, and if square brackets are added I want a span to be added around the text to make the text green. Here is my code so far:
function greenText() {
var textAreaText = $('#textarea').val();
var replacedText = textAreaText.replace("[", "<span style='color:green'>").replace("]", "</span>");
$('#preview').html(replacedText);
}
$(function() {
greenText();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="preview" style="height: 4em; background-color:#eee; padding:10px;"></div>
<textarea id="textarea" rows="4" cols="50" onchange="greenText();" onkeyup="this.onchange();" onpaste="this.onchange();" oninput="this.onchange();">
At w3schools.com you will learn how to [make a website].
</textarea>
The greenText
function works when the page loads, however when I am adding in brackets updating the preview
div it prints the square brackets out to the page rather than the span tags. Does any one have any idea why the function isn't replacing the text?