I want to create a rectangle whenever somebody click on "try it" button I will ask number of line from user and it will print same line row and column to form a rectangle. But when I ran this code, I will get nothing on my DOM and its says in console that str is not defined at line 27, but I already defined it, don't know where the problem is
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<body>
<div class="container">
<p>Click the button to demonstrate the prompt box.</p>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<script>
const myFunction = () => {
let insertLine = prompt("put the no. of lines Here: ");
let str = "";
for (i = 0; i < insertLine; i )
for (j = 0; j < i; j ) {
str = "*";
}
str = "\n";
};
console.log(str);
document.getElementById("demo").innerHTML = str;
</script>
</div>
</body>
</html>
CodePudding user response:
You try to use the "str" variable outside of it's definition scope :
You defined str
in MyFunction
but you use it outside when you try to log it.
CodePudding user response:
I am not sure I understood your problem, but the console.log() and the document.getElementById() should be inside your function. Your for loop also needed changes to print the complete rectangle. Try this code and let me know if it works.
const myFunction = () => {
let insertLine = prompt("put the no. of lines Here: ");
let str = "";
for (i = 0; i < insertLine; i ) {
for (j = 0; j < insertLine; j ) {
str = "*";
}
str = "<br/>";
}
console.log(str);
document.getElementById("demo").innerHTML = str;
};