0

i'm makeing score counter and i'm trying to display a message with the value of my winning score input (Where the player chooses how many points to play).

When I use input.value outside the array, it works fine. But when I try to use it within the array, it returns me 0.

var input = document.querySelector("#scoresInput");
var msgWindow = document.querySelector("#msgWindow");
var wsDisplay = document.querySelector("p span") // winning score display


input.addEventListener("change", function(){
    if(this.value <= 0){
    msg("errorMsg", 2);

    }else{
    msg("newMsg", 1);
    wsDisplay.textContent = this.value;
    }
});

var msgIndex = [
    "new game begins now you play to " + input.value + " scores",
    "you can't play to " + input.value + " scores(",
    "! player 1 is the winner!",
    "! player 2 is the winner!"
];

function msg(msgClass, i){
    msgWindow.classList.add(msgClass);
    msgWindow.textContent = msgIndex[i];
}
    <h1><span id="p1Display">0</span> - <span id="p2Display">0</span</h1>
    <p>you play to <span>3</span></p>

<input id="scoresInput" type= "number">
<button id="p1">player1</button>
<button id="p2">player2</button>
<button id="reset">newGame</button>
<p id="msgWindow"></p>

//I expect the real time output of the input value but input.value in the array always return 0.

1
  • You're setting msgIndex when the page first loads, not after the user enters something in the input field. Commented Sep 13, 2019 at 9:15

1 Answer 1

1

Using a variable in an array value copies the value at the time you execute the assignment, it doesn't make it re-evaluate the variable each time the array is used.

You can put a placeholder in the string, and replace it in your msg() function.

If you need more replacements like this, you should find a template library that automates it.

var input = document.querySelector("#scoresInput");
var msgWindow = document.querySelector("#msgWindow");


input.addEventListener("change", function() {
  if (this.value <= 0) {
    msg("errorMsg", 2);

  } else {
    msg("newMsg", 1);
    //wsDisplay.textContent = this.value;
  }
});

var msgIndex = [
  "new game begins now you play to {INPUTVALUE} scores",
  "you can't play to {INPUTVALUE} scores(",
  "! player 1 is the winner!",
  "! player 2 is the winner!"
];

function msg(msgClass, i) {
  msgWindow.classList.add(msgClass);
  msgWindow.textContent = msgIndex[i].replace('{INPUTVALUE}', input.value);
}
<input id="scoresInput" type="number">
<button id="p1">player1</button>
<button id="p2">player2</button>
<button id="reset">newGame</button>
<p id="msgWindow"></p>

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.