I'm trying to have my html call a javascript function onclick in which the function itself references the event that called it, but I keep getting this error:
Uncaught TypeError TypeError: Cannot set properties of undefined (setting 'value')
at play (c:\Users\C2Ran\Desktop\Practice\app.js:5:16)
at onclick (c:\Users\C2Ran\Desktop\Practice\index.html:24:68)
Here's my html:
<!DOCTYPE html>
<head>
<link rel="stylesheet" href="style.css">
<script type="text/javascript" src="app.js" defer></script>
</head>
<body>
<input type="button" value="X" id="turn" onclick="play(this);">
</body>
</html>
Here's my javascript:
var turn = "X"
function play(event) {
var cell = event.target;
cell.value = turn;
console.log(turn);
if(turn == "X")
{
turn = "O"
}
else
{
turn = "X"
}
}
Is there something I'm missing? Why is it saying value
is undefined? Is it not getting the event correctly? Or does onclick not count as an event? I also tried event.currentTarget
instead
CodePudding user response:
Avoid using function calling in HTML attributes, instead use addEventListener
,
Your problem is that you are using this
when you should be using event.currentTarget
Note: I've improved a bit your code in play()
function
function play(cell) {
cell.value = cell.value === "X" ? "O" : "X"
console.log(cell.value);
}
document.getElementById('turn').addEventListener('click', e => play(e.currentTarget))
<input type="button" value="X" id="turn">