0

I have a while loop that loops 6 times, each time its loops a TD element is create as well as setting an id to it, the problem im having is that the id for everysingle one of the TDs is having the last result of the loop.

var table = document.getElementById("table_calendar");
var tr = document.createElement("tr");
var td;
var days_displayed = 1;
while(i<=6){
    td = document.createElement("td");
    td.innerHTML = days_displayed;
    td.classList.add("tdd");
    td.id = year+"-"+month +"-"+days_displayed;
    console.log(days_displayed);
    td.onclick = function(){
        alert(td.id);
    };
    days_displayed++;
    i++;
    tr.appendChild(td);
}
table.appendChild(tr);

The alert function is showing this for any TD that I click 2018-02-6

The innerHTML is having different values such as 1 2 3 4 5 6

Am I missing something?

1 Answers1

0

You should access the id of the HTML element using this:

var table = document.getElementById("table_calendar");
var tr = document.createElement("tr");
var td;
var days_displayed = 1;
var year = "2028"
var month = "02"
var i = 0
while(i<=6){
    td = document.createElement("td");
    td.innerHTML = days_displayed;
    td.classList.add("tdd");
    td.id = year+"-"+month +"-"+days_displayed;
    console.log(days_displayed);
    td.onclick = function(){
        alert(this.id);
    };
    days_displayed++;
    i++;
    tr.appendChild(td);
}
table.appendChild(tr);
<table>
  <tr id="table_calendar">
  </tr>
</table>

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this

What happens here is that your td.id will return the last element created, because it has been declared as a var outside the loop. The scope of var is not limited to the block inside {}. If you want the variable to be block scoped you have to use let instead:

var table = document.getElementById("table_calendar");
var tr = document.createElement("tr");
var days_displayed = 1;
var year = "2028"
var month = "02"
for(let i = 0; i <= 6; i++){
    let td = document.createElement("td");
    td.innerHTML = days_displayed;
    td.classList.add("tdd");
    td.id = year+"-"+month +"-"+days_displayed;
    console.log(days_displayed);
    td.onclick = function(){
        alert(td.id);
    };
    days_displayed++;
    tr.appendChild(td);
}
table.appendChild(tr);
<table>
  <tr id="table_calendar">
  </tr>
</table>

What's the difference between using "let" and "var" to declare a variable?

Greetings

messerbill
  • 5,499
  • 1
  • 27
  • 38