Menu ▼



Posted By :
avatarmrkraju
Total Views : 610

Show html code as text in div using jquery

This example shows you how to show the html as text in div using jquery with out rendering. By using jquery text() function we can assign the html code to div and additionally we have to replace the space with &nbsp; and new line(\n) with html <br/>

jQuery code

<script language="javascript">
    $(document).ready(function () {
        $("#txtInput").on("keyup", function () {
            $("#divOutput").text($("#txtInput").val());
            $("#divOutput").html($("#divOutput").html().replace(/\n/g, '<br/>').replace(/ /g, '&nbsp;'));
        });
    });
</script>

Example

Enter or copy paste html code in the below textbox


Output

Source code

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
    <script type="text/javascript" src="http://code.jquery.com/jquery-1.7.2.min.js"></script>
    <script language="javascript">
        $(document).ready(function () {
            $("#txtInput").on("keyup", function () {
                $("#divOutput").text($("#txtInput").val());
                $("#divOutput").html($("#divOutput").html().replace(/\n/g, '<br/>').replace(/ /g, '&nbsp;'));
            });
        });
    </script>
</head>
<body>
    Input<br />
    <textarea id="txtInput" rows="20" style="width: 100%;"></textarea>
    <br />
    <br />
    <div id="divOutput" style="border: solid 1px #ccc; padding: 20px; background: #ffe;">
    </div>
</body>
</html>






comments powered by Disqus


Search dotnetlearners.com