[Solved] Why clicking the button is not giving a valid text in JS?


Your first line of the buttonData function changes the value of btnVal[card.id] to 1 if the value is 0, so you never get the first case:

btnVal[card.id] = ! btnVal[card.id] ? 1 : btnVal[card.id] == 2 ? 0 : btnVal[card.id] + 1;

In the above, your first ternary says if btnVal[card.id] is falsey (which 0 is) the set btnVal[card.id] to 1. After that you go through your switch case with btnVal[card.id] = 1.

Assuming that you’re not expecting other falsey values, you can either remove this ternary completely, or else have btnVal[card.id] !== undefined rather than !btnVal[card.id].

[EDIT] You can replace the above line with:

btnVal[card.id] = btnVal[card.id] !== undefined ? 1 : btnVal[card.id] == 2 ? 0 : btnVal[card.id] + 1;

Or, if you are sure the functionality is correct then put this line at the end of the function, so you are only changing the value after you use it.

The full function then becomes:

function buttonData(card.id) {
  // store the current value of the card id if it exists, or zero.
  const value = btnVal[card.id] || 0;
  // increase the btnVal number 
  btnVal[card.id] = value > 1 ? 0 : value + 1;
  switch(btnVal[card.id]) {
    case 0:
      return {
        target: card.id,
        content1 : "Nice to code using Js",
      };
    case 1:
      return {
        target: card.id,
        content2 : "Nice to code using JQuery",
      };
    case 2:
      return {
        target: card.id,
        content1 : "Hello",
        content2 : "Greetings",
      };
    default:
      return {};
  }
}

6

solved Why clicking the button is not giving a valid text in JS?