Reputation:
i am trying to make a try it your self like in w3school and i need help. this is where i get so far:
<input value="Update page" type="button">
<textarea id="mycode"></textarea>
<iframe id="display"></iframe>
another tryityourself:
<input value="Update page" type="button">
<textarea id="mycode"></textarea>
<iframe id="display"></iframe>
$(document).ready(function() {
$('input:button').on('click', function() {
var x = $(this).next().val();
frames['display'].document.documentElement.innerHTML = x;
});
});
but what i want is the html will show in the iframe near the closest textarea.
i hope you understand what i mean.
please help me.
Upvotes: 0
Views: 121
Reputation: 111
You need to restructure your markup a little and use jQuery to access the iFrame. I took your code and reworked it into a functional example. Note the use of classes instead of ids.
You can manipulate the contents of the iFrame using standard jQuery:
<div class="codeFrame">
<input value="Update page" type="button">
<textarea class="mycode"></textarea>
<iframe class="display"></iframe>
</div>
<div class="codeFrame">
<input value="Update page" type="button">
<textarea class="mycode"></textarea>
<iframe class="display"></iframe>
</div>
<script type="text/javascript">
$(document).ready(function() {
$('input:button').on('click', function() {
var codeFrame = $(this).parent('.codeFrame');
codeFrame.children('iframe').contents().find('body').html(codeFrame.children('textarea').val());
});
});
</script>
Upvotes: 2
Reputation: 292
Off the top of my head there's one of two ways you can handle this. The first is to take your code as a string, encode it using base64, then set the iframe src to "data:text/html,<base64 encoded html here>" and it should work. You can read more about this method here, Is it possible to "fake" the src attribute of an iframe?
Option two, is to post your code to a server, generate a temporary html file using php or some server side language, return an id, then change the src of the iframe to a viewer php file with the returned id at the end which will display the html file it wrote to the server, then delete it just to keep your file system clean.
An example is like this, your browser makes an ajax request to form post domain_a.com/postform.php, postform.php writes the contents of the html to 1.html and returns 1 to your javascript, then your javascript sets the src of the iframe to domain_a.com/viewhtml.php?id=1 where the viewhtml.php will open 1.html, read it, display it and then delete it afterwards.
Upvotes: 0