Ritesh Bhat
Ritesh Bhat

Reputation: 3

How to prevent unwanted line breaks before the table is printed

When button is clicked the control goes to the Javascript function print() and the table gets printed. But, it's showing almost 20 line breaks before the table gets printed and I want to prevent it.

<!DOCTYPE html>
<html>
<head>
	<script type="text/javascript">
	var print=function()
	{
		document.write("<table border=5px>");
		for(var i=1;i<1001;i++)
		{
			document.write("<tr>"+"<td>"+i+"</td>"+"</tr>"+"</br>");
		}
		document.write("</table>");
	}
	</script>
</head>
<body style="white-space: nowrap">
	<input type="button" value="click here" onclick="print();" />
</body>
</html>

Upvotes: 0

Views: 338

Answers (2)

James Ives
James Ives

Reputation: 3365

This is happening because you have a <br> tag in your for loop. If you want to have a linebreak between each table when you click your button that generates them you'll need to add the line break tag to the end of the closing table. (Or use CSS to create padding / margins)

var print=function() { 
document.write("<table border=5px>"); 
for(var i=1;i<1001;i++) { 
document.write("<tr>"+"<td>"+i+"</td>"+"</tr>");  } 
document.write("</table> <br>"); }

Otherwise just remove it entirely.

var print=function() { 
document.write("<table border=5px>"); 
for(var i=1;i<1001;i++) { 
document.write("<tr>"+"<td>"+i+"</td>"+"</tr>");  } 
document.write("</table>"); }

Upvotes: 0

Keammoort
Keammoort

Reputation: 3075

Remove closing <br> tag from your string:

var print=function()
{
    document.write("<table border=5px>");
    for(var i=1;i<1001;i++)
    {
        document.write("<tr>"+"<td>"+i+"</td>"+"</tr>"); // </br> removed here
    }
    document.write("</table>");
}

Upvotes: 3

Related Questions