How can I prevent this from happening when i press the button?
Instead of printing below the other output above, I want it to replace what is already there.
First click:

Second click:

Code:
var sq = "";
var outSquare = document.getElementById("outSquare");
var inSquare = document.getElementById("inSquare");
var bSquare = document.getElementById("bSquare");
bSquare.onclick = function () {
var g = inSquare.value;
outSquare.innerHTML = square(g);
}
function square(a) {
for (var i = 1; i <= a; i++ ) {
for (var j = 1; j <= a; j++) {
sq += "*";
}
sq += "<br>";
}
return sq;
}
<p id="outSquare"></p>
<input id="inSquare" type="number"/>
<button id="bSquare" type="button"> Print </button>
You need to initialise sq inside the function too:
var sq = "";
var outSquare = document.getElementById("outSquare");
var inSquare = document.getElementById("inSquare");
var bSquare = document.getElementById("bSquare");
bSquare.onclick = function () {
var g = inSquare.value;
outSquare.innerHTML = square(g);
}
function square(a) {
sq = ""; // empty this string on click
for (var i = 1; i <= a; i++ ) {
for (var j = 1; j <= a; j++) {
sq += "*";
}
sq += "<br>";
}
return sq;
}
<p id="outSquare"></p>
<input id="inSquare" type="number"/>
<button id="bSquare" type="button"> Print </button>
You are missing sq = ''; inside the function square(a). Doing sq="" will re-initialize the value of sq to empty for new iteration and will output the desired behaviour.
var sq = "";
var outSquare = document.getElementById("outSquare");
var inSquare = document.getElementById("inSquare");
var bSquare = document.getElementById("bSquare");
bSquare.onclick = function() {
var g = inSquare.value;
outSquare.innerHTML = square(g);
}
function square(a) {
sq = '';
for (var i = 1; i <= a; i++) {
for (var j = 1; j <= a; j++) {
sq += "*";
}
sq += "<br>";
}
return sq;
}
<p id="outSquare"></p>
<input id="inSquare" type="number" />
<button id="bSquare" type="button"> Print </button>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With