0

I am fairly new to Javascript and i ran into a problem when creating a chess game . I have already made the board, but when i tried incorporating JS code that would move these peices when i clicked on them, a problem arose. See i declared the variable "x" to hold the value of the chess peice value that had been clicked on when count=0 but when i tried it out, the code just outputs x as 'undefined'.What have i done wrong, any help would be appreciated :)

(below is a snippet of my JS code)

<div onclick="changeText(63)"id="63"class="black">&#9816;</div>
<div onclick="changeText(64)"id="64"class="white">&#9814;</div>
</div>
<script>
var count = 0;
var x;
function changeText(id) {
    if (count > 1){
        count = 0;
    }
    if(count=0){
        x = document.getElementById(id).innerHTML;
        document.getElementbyId(id).innerHTML="";
    }
    if(count=1){
        document.getElementById(id).innerHTML=x;
    }
    count = count + 1;
}
</script>

2 Answers2

1

The second and third if statements will not be evaluating the variable value - because rather than comparison (count=== 0) what happens there is a variable assignment (count = 0).

The if (count = 0) is evaluated to false, so, the variable x never gets a value.

On the other hand if (count = 1) is evaluated to true. So, the HTML element gets an undefined string. Your code should look like this:

...

if (count === 0){
    x = document.getElementById(id).innerHTML;
    document.getElementbyId(id).innerHTML="";
}

if( count === 1){
    document.getElementById(id).innerHTML=x;
}

Reference: https://www.w3schools.com/js/js_comparisons.asp

Charlie
  • 22,886
  • 11
  • 59
  • 90
  • I put alert("Count=0"); in the first if statement and alert("Count=1"); in the second if statement to see if it was setting count to 1 but no matter when and where i clicked i got the alert: "Count=0". – The Voyager Jul 31 '21 at 06:07
  • The alert prints your string. – Charlie Jul 31 '21 at 06:21
  • yes but it should alert me with "Count=1" every second time i click on a square, as i put the different alert statements in separate if statements – The Voyager Jul 31 '21 at 06:23
0

You don't need to pass the id to that handler function if it's doing the same thing. If you want a function that changes the innerHTML of the thing that was clicked, try passing event to the handler, and then using event.target.innerHTML like this:

<div onclick="changeText(event)" class="black">&#9816;</div>
<div onclick="changeText(event)" class="white">&#9814;</div>

<script>
function changeText(event) {
    if (event.target.innerHTML === 'x') {
    event.target.innerHTML = 'y' // you can do anything here
  } else {
    event.target.innerHTML = 'x'
  }
    
}
</script>
Matt
  • 251
  • 1
  • 5