0

My program is when all the three cells have been clicked, all the color of the cell will be appeared in green. In my Javascript program, there is a code line "countx = 1", the idea is to assign a value "1" to the variable count1, count2, count3, so i expected the values of these three variable will all be "1" after i have clicked all the three cells. However, you see i have applied the console.log to check their value after the selected cell function, they are kept "0".

What is wrong in my program and how to correct it? I want to keep using the method "let num = idname.charAt(idname.length-1); countx = 'count' + num".

var count1 = 0;
var count2 = 0;
var count3 = 0;

function init(event) {
  selectedcell();

  function selectedcell() {
    let idname = event.target.id;
    let num = idname.charAt(idname.length - 1);
    countx = 'count' + num
    console.log('countx = ', countx)
    countx = 1;
    console.log(countx);
  }

  console.log(count1);
  console.log(count2);
  console.log(count3);

  if (count1 == 1 && count2 == 1 && conunt3 == 1) {
    document.getElementById("cell1").style.backgroundColor = "green"
    document.getElementById("cell2").style.backgroundColor = "green"
    document.getElementById("cell3").style.backgroundColor = "green"
  }
}

init(event);
body {
  height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 20px;
  position: relative;
}

* {
  margin: 0;
  box-sizing: border-box;
}

.rows {
  display: flex;
}

.cells {
  color: rgb(255, 255, 255);
  border: 1px solid rgb(44, 18, 236);
  font-size: 5rem;
  height: 6rem;
  width: 6rem;
  align-self: center;
  text-align: center;
}
<div class="rows">
  <div class="cells" id="cell1" onclick="init(event)"></div>
  <div class="cells" id="cell2" onclick="init(event)"></div>
  <div class="cells" id="cell3" onclick="init(event)"></div>
</div>
Mushroomator
  • 6,516
  • 1
  • 10
  • 27
eric2023
  • 9
  • 2
  • 1
    _"What is wrong in my program"_ - `countx` is a variable named `countx`, no more, no less - it does not magically access anything else. _"and how to correct it?"_ - ideally, by not using "numbered" variable names in the first place, but an array instead. If you really want to go the "variable variables" route, then - see duplicate. – CBroe Aug 07 '23 at 11:00
  • @CBroe, the duplicate seems use jquery, i only know javascript... – eric2023 Aug 07 '23 at 11:12
  • Almost nothing in there is jQuery. As far as I can see, it only gets used in one _example_, and there only to select an element to initialize a DataTable on (which has little to do with your problem in the first place.) – CBroe Aug 07 '23 at 11:15

0 Answers0