Harry Martland
Harry Martland

Reputation: 624

Javascript text field live view

I am trying to make a similar bit of code like at the bottom of this page to leave a comment. I have the basic code but the output does not register new lines (or HTML, but that isn't important). I have the function below called on key-up on the text field. Any help would be greatly appreciated. Thanks

Here is the whole page (Now working)

<html>
<body>

<form>
    <textarea id="text" onkeyup="outputText()"></textarea>
</form>

<div id="outputtext" style="width:500px;">
</div>

</body>

<script type="text/javascript">
    function outputText()
    {
        var text = document.getElementById('text').innerHTML;
        document.getElementById('outputtext').innerHTML = (text + '').replace(/([^>\r\n]?)(\r\n|\n\r|\r|\n)/g, '$1<br>$2');
    }
</script>

</html>

Upvotes: 0

Views: 1013

Answers (4)

MikeM
MikeM

Reputation: 27405

You can use the <pre> (preformatted) tag so that html and carriage returns are represented without doctoring the field input

html:

<input id="text" type="text" />
<pre id="outputtext"></pre>

jQuery:

$(document).ready(function () {
    $('#text').keyup(function () {
        $('#outputtext').html($(this).val());
    });
});

Upvotes: 0

bigblind
bigblind

Reputation: 12867

document.getElementById('outputtext').innerHTML = (text + '').replace(/([^>\r\n]?)(\r\n|\n\r|\r|\n)/g, '$1<br>$2')

Upvotes: 3

Bas Slagter
Bas Slagter

Reputation: 9929

I think it's good for you to take a look at how tools like jQuery can make your live easier in this kind of cases. Your particular question is a bit unclear however...can you give us more details?

Upvotes: 0

asgs
asgs

Reputation: 3984

Have you tried getting the textarea contents as

var text = document.getElementById('text').value; instead?

Upvotes: 0

Related Questions