Forum Moderators: open

Message Too Old, No Replies

Comment preview fucntion?

         

zyph

6:59 pm on Nov 25, 2004 (gmt 0)

10+ Year Member



Hi,

I'm looking for a method of grabbing the info one writes in some input/textarea fields, and the printing the info out *live*.

Like a live-preview of the comment one is currently writing.

djclark

2:03 am on Nov 26, 2004 (gmt 0)

10+ Year Member



Do you mean something like the following?

function LiveUpdate(source,dest)
{
dest.innerHTML = source.value.replace("\n","<br>");
}

<textarea rows="5" cols="50" id="myTextBox" onchange="LiveUpdate(this;document.getElementById('LiveDisplay'))"></textarea>

<p id="LiveDisplay"></p>

Bernard Marx

9:06 am on Nov 26, 2004 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



onKeyUp perhaps?

zyph

2:04 pm on Nov 27, 2004 (gmt 0)

10+ Year Member



I have not much experience in JS, but it looks quite right. But it doens't work?

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
<head>
<title>LiveUpdate with JS</title>
<script Language="javascript">
function LiveUpdate(source,dest)
{
dest.innerHTML = source.value.replace("\n","<br>");
}
</script>
</head>
<body>

<textarea rows="5" cols="50" id="myTextBox" onchange="LiveUpdate(this;document.getElementById('LiveDisplay'))"></textarea>
<p id="LiveDisplay"></p>


</body>
</html>

Bernard Marx

3:09 pm on Nov 27, 2004 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Three small things:

1. The arguments are separated by a semicolon ';' in the function call. Should be a comma.

2. For the update to be really 'live', you need to use the onKeyUp event handler. onchange only fires when the textarea loses focus.

So..

onKeyUp="LiveUpdate(this,document.getElementById('LiveDisplay'))"

3. To replace all instances of \n in the value string you need to use a regular expression with the 'g' modifier (global) as first arg.

dest.innerHTML = source.value.replace(/\n/g,"<br>");

That should now work.

zyph

3:14 pm on Nov 27, 2004 (gmt 0)

10+ Year Member



This is so brilliant! Works perfectly, thanks alot :)

djclark

10:06 pm on Nov 28, 2004 (gmt 0)

10+ Year Member



sorry .... i wrote it out quickly and didnt test....

so the ; was a typo....