1

I'm making chess in JavaScript and I have a variable that is supposed to be defined when I click on a button and then when I click on another button that ones value is supposed to change to the variable. I've already made sure that the variable does in fact define as it should after the first click but for some reason the variable becomes "undefined" when I click the second time.

var action = 1;
function Find_Piece(clicked_id, Piece)
{
    if (action == 1)
    {
        var Piece = document.getElementById(clicked_id).value;

        alert(Piece)

        action = 0;
    }
    else if (action == 0)
    {
        document.getElementById(clicked_id).value = Piece;

        action = 1;
    }
}

Every time I click a button it stores the name of the piece in the variable Piece. This variable becomes "undefined" when the function is ran again.

Why is this, and how do I fix it?

I have tried removing all unnecessary code but to no avail. I expect the piece to be kept in memory and used again when the function is ran a second time

Ivar
  • 6,138
  • 12
  • 49
  • 61
  • 2
    "_I expect the piece to be kept in memory and used again when the function is ran a second time_" - You declare `Piece` inside of your function, so it only exists within the function (and is forgotten as soon as the function ends). You seem to already know that given that `action` has been declared outside of the function. Why not apply the same to `Piece`? – Ivar Oct 27 '22 at 11:12
  • 2
    AND you need to remove the param "Piece" from the function, so `function Find_Piece(clicked_id)` otherwise it's gonna stay undefined. – Kathara Oct 27 '22 at 11:13
  • Because I have to declare it when a button is clicked and only the first time I click a button. I was unable to find a way of doing this outside of the function but please do tell me if you know a way. – Erik Hortlund Oct 27 '22 at 11:15
  • 2
    @ErikHortlund Declare `Piece` above your function, remove the `var` from within the function so you _assign_ a value to it without declaring it (leaving it there will overshadow the lexical `Piece` that you declare). Then also remove it from your parameters as Kathara mentioned and you should be good to go. – Ivar Oct 27 '22 at 11:17

0 Answers0