728883902
728883902

Reputation: 507

HTML code from text area rendered in DIV

I've searched high and low for a solution to my problem but unfortunately could not find anything of use, so I was wondering if you guys could help me.

I want the HTML code typed into a text area to be rendered in a DIV element on the same page, in real-time. At the moment, I have:

$('#codeBox').keyup(function() {
    var keyed = $('#codeBox').val();
    $("#preview").html(keyed);
});

I hope I formatted that correctly. This may well be (and normally is) a case of 'the answer was right in front of me all along', sorry if that's the case!

Is there a problem with my code? Could you guys suggest an alternative?

Thank you in advance.

Upvotes: 0

Views: 727

Answers (1)

Abraham Hamidi
Abraham Hamidi

Reputation: 13789

You cannot put greater than and less than signs in an element's innerHTML, so you need to use Entities because of greater than and less than signs:

$('#codeBox').keyup(function() {
  var keyed = $('#codeBox').val();
    keyed = keyed.replace(/</g, "&lt;")
    keyed = keyed.replace(/>/g, "&gt;")
  $("#preview").html(keyed);
});

DEMO

Upvotes: 1

Related Questions