krishk varma
krishk varma

Reputation: 73

JavaScript showing only last result

I am trying to print the years in which Sunday comes in 1st January. The problem is that it's only showing the last result.

function sun() {
  var sunday = new Date();
  var year;
  for (year = "2014"; year <= 2050; year++) {
    var date = new Date(year, 0, 1);
    if (date.getDay() == 0)
      document.getElementById('demo').innerHTML = "First Jan being sunday on year =" + year + "<br>";
  }
}
<input type="submit" id="submit" onclick="sun()">

Upvotes: 1

Views: 121

Answers (4)

Alessio Cantarella
Alessio Cantarella

Reputation: 5201

You should put "January 1st will be on Sunday in:" statically inside the '#demo' div, then concatenate the years by using += instead of =, e.g.:

function sun() {
  for (let year = 2014; year <= 2050; year++) {
    if ((new Date(year, 0, 1)).getDay() == 0) {
      document.getElementById('demo').innerHTML += " " + year;
    }
  }
}
<input type="submit" id="submit" onclick="sun()">
<div id="demo">January 1st will be on Sunday in:</div>

Upvotes: 1

Helper
Helper

Reputation: 847

The values are getting replaced in each iteration of the loop.

Concatenating the result is going to help.

Use the operator + in the expression:

document.getElementById('demo').innerHTML += "First Jan being sunday on year ="+year+"<br>"; 

Upvotes: 2

GrahamTheDev
GrahamTheDev

Reputation: 24885

function sun(){

var sunday = new Date();
var year;

for (year = "2014"; year <= 2050; year++){
    var date = new Date(year,0,1);
    if (date.getDay()==0)
    //you are overwriting the content of 'demo' each time, changed to "+=" so it adds new HTML each time
    document.getElementById('demo').innerHTML += "First Jan being sunday on year ="+year+"<br>"; 
}

}

Upvotes: 1

Rebai Ahmed
Rebai Ahmed

Reputation: 1600

Add + to your expression

 document.getElementById('demo').innerHTML += "First Jan being sunday on year ="+year+"<br>"; 

Upvotes: 1

Related Questions