Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Tic tac toe javascript. Make it so X and 0 can only be pressed once, not overwrite eachother

How can i make so that X and 0 cant overwrite and only be pressed once on every space.


const inputs = document.querySelectorAll("input")
let clicks = 1;
for (let input of inputs) {
    input.addEventListener('click', (evt) => { 
        input.value = ("0") 
        const id = evt.target.id;
        const buttonNr = id[1];
        if (clicks % 2 === 0)  {
            if(input.value = "X") 
            console.log(`Player X pressed ${buttonNr}`);
        } else {
            console.log(`Player 0 pressed ${buttonNr}`);
        } 
        clicks++ 
    })
         


        }


I tried input.value = "" return; but that did not work unless i put it at the wrong place.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Try this:

const inputs = document.querySelectorAll("input")
let clicks = 1;
for (let input of inputs) {
    input.addEventListener('click', (evt) => {
        // Make sure input is empty
        if(evt.target.value == "") {
            // Increment "clicks"; check if (clicks modulo 2) == 0;
            // if true place an "X" otherwise place an "O".
            evt.target.value = (clicks++ % 2 == 0) ? "X" : "O";
        }
    })
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading