0

I have made a textbox and an iframe in the same html. I want to load the 'html' rendered from textbox into html. I am using javascript button click event, but nothing is getting rendered. Pls help, I cant find where I am making mistake!

HTML:

<button onClick="convert()">Run</button> <textarea id="mycode"> Hello World! </textarea> <iframe id="display"></iframe> 

Javascript:

function convert() { var x = document.getElementById('mycode').value; document.getElementById('display').innerHTML = x; } 

Can someone help, what's wrong ?

4 Answers 4

2

Try setting src of iframe to data URI representation of textarea value x

function convert() { var x = document.getElementById('mycode').value; document.getElementById('display').src = "data:text/plain," + x; }
<button onClick="convert()">Run</button> <textarea id="mycode"> Hello World! </textarea> <iframe id="display"></iframe>

Sign up to request clarification or add additional context in comments.

Comments

1

Just replace

document.getElementById('display').innerHTML = x; 

with

document.getElementById('display').contentWindow.document.body.innerHTML = x 

Comments

1

You can't manipulate an iframe with Javascript (or jQuery) because the iframe is essentially a separate webpage. This is for security purposes, to prevent one website from embedding a malicious script into an iframe that can target the host page. There is no way around it, as far as I know. Generally it's not good practice to use iframes.

Comments

1

I was browsing the answers for the same task. Well the accepted answer does help a little but the main task is to render "HTML". It works using the srcdoc attribute of the iframe tag.

function convert() { var x = document.getElementById('mycode').value; document.getElementById('display').srcdoc = x; }
<button onClick="convert()">Run</button> <textarea id="mycode"> <!-- Comment is not rendered --> Hello World! </textarea> <iframe id="display"></iframe>

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.