Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Overwrite paragraph button.onclick()

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>
like image 683
Meek Avatar asked Feb 12 '26 10:02

Meek


2 Answers

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>
like image 196
Aagam Jain Avatar answered Feb 14 '26 22:02

Aagam Jain


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>
like image 27
Ankit Agarwal Avatar answered Feb 14 '26 22:02

Ankit Agarwal



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!