Reputation: 499
The below code is my html code
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
<link rel="stylesheet" type="text/css" href="CssText.css">
</head>
<body>
<form>
Enter number of rows: <input type="text" name="t1" /> <input
type="button" value="Display Diomond"
onclick="return myFunction(this.form)" />
</form>
<p id="p"></p>
<script src="StarPrint.js"></script>
</body>
</html>
The below code is my javascript code
function myFunction(form) {
var no;
no = form.t1.value;
no = no / 2;
var no2 = no;
var no3 = no;
var no4 = no;
var no5 = no;
var no6 = no;
for ( var i = 0; i < no; i++) {
for ( var index = 0; index < no2; index++) {
document.getElementById("p").innerHTML ="  ";
}
no2 = no2 - 1;
for ( var index2 = 0; index2 < (i * 2) + 1; index2++) {
document.getElementById("p").innerHTML = "*";
}
document.getElementById("p").innerHTML="</br>";
}
document.getElementById("p").innerHTML="  ";
for ( var i = 0; i < no3 + 1; i++) {
for ( var index = 0; index <= i; index++) {
document.getElementById("p").innerHTML = "  ";
}
for ( var index2 = 0; index2 < (no4 * 2) - 3; index2++) {
document.getElementById("p").innerHTML = "*";
}
no4 = no4 - 1;
document.getElementById("p").innerHTML = "</br> ";
}
}
I want to print pattern of diamond structure.The above program was working when I used document.write instead of document.getElementById("p").innerHTML with some modification.Where is that error I am not getting it.
Upvotes: 0
Views: 87
Reputation: 35793
You are replacing the content of p
every time you call document.getElementById("p").innerHTML =
.
Instead, save the text into a variable and only assign it to p
at the end:
function myFunction(form) {
var no;
no = form.t1.value;
no = no / 2;
var no2 = no;
var no3 = no;
var no4 = no;
var no5 = no;
var no6 = no;
var diamond = "";
for ( var i = 0; i < no; i++) {
for ( var index = 0; index < no2; index++) {
diamond +="  ";
}
no2 = no2 - 1;
for ( var index2 = 0; index2 < (i * 2) + 1; index2++) {
diamond += "*";
}
diamond+="</br>";
}
diamond+="  ";
for ( var i = 0; i < no3 + 1; i++) {
for ( var index = 0; index <= i; index++) {
diamond += "  ";
}
for ( var index2 = 0; index2 < (no4 * 2) - 3; index2++) {
diamond += "*";
}
no4 = no4 - 1;
diamond += "</br> ";
}
document.getElementById("p").innerHTML = diamond;
}
Working Example - http://jsfiddle.net/fdadE/
Upvotes: 2
Reputation: 3778
You are not appending the stuff you want, but just assigning. Replace all =
with +=
like below:
document.getElementById("p").innerHTML = "  ";
to
document.getElementById("p").innerHTML += "  ";
Upvotes: 1