Forum Moderators: open
But the output is "5 undefined" (After entering 4
words in the text box).
Please tell me how to correct this.
Bellow is the complete code.
====
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>Ordered Words</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<script type="text/javascript">
<!--
document.writeln("<table>");
function order()
{
var words=inputform.inputdata.value.split("\n");
for (var i=0; i<words.length; i++)
document.writeln("<tr> <td>");
document.writeln(i+1);
document.writeln("</td> <td>");
document.writeln(words[i]);
document.writeln("</td> </tr>");
}
document.writeln("</table>");
//-->
</script>
</head>
<body>
<form name="inputform" action="">
<textarea name="inputdata" rows="10" cols="40"></textarea>
<input name="generate" type="button" value="Generate" onClick="order()">
</form>
</body>
</html>
1. using document.writeln after the document has been rendered in the browser usually is not a good idea, as it may replace the original content.
2. if you're using more than one statement in a for-loop, the statements must be enclosed with brackets { and }.
Try this:
<script type="text/javascript">
<!--
function order()
{
var output = "<table>";
var words=inputform.inputdata.value.split("\n");
for (var i=0; i<words.length; i++)
{
output += "<tr> <td>" + (i+1) + "</td> <td>";
output += words[i];
output += "</td> </tr>";
}
output += "</table>";
document.getElementById('result').innerHTML = output;
}
//-->
</script>
</head>
<body>
<form name="inputform" action="">
<textarea name="inputdata" rows="10" cols="40"></textarea>
<input name="generate" type="button" value="Generate" onClick="order()">
</form>
<div id="result"></div>
The script stores the output in a variable while looping through the array. It then 'writes' it into the innerHTML-property of a special <div>.