0

So I want to save input data into a variable and see if it fill the requirement. But what happens here is when I run the program and the name is more than 6 letters(which should be) I still get the error that the name should contain 6 letters. What am I doing wrong here?

let oGameData = {};


var nick1 = document.getElementById('nick1').value;
var nick2 = document.getElementById('nick2').value;

oGameData.nickNamePlayerOne = nick1;
oGameData.nickNamePlayerTwo = nick2;


function validatform(e){
const message = [];

if(oGameData.nickNamePlayerOne.length < 6 || oGameData.nickNamePlayerTwo.length < 6){
    message.push("your name must be more then 6 letters!!");
    console.log(message);
}


if(message.length > 0){
    e.preventDefault();
    errormasg.innerText = message.join(", ");
    let np = document.createElement("p");
    np.setAttribute("class", "errorMsg");
    errormasg.appendChild(np);
}
if(message.length == 0){
    initiateGame();
}
masih
  • 1
  • 1

1 Answers1

1

You're saving the value into a variable when the script first runs and not when the validatform function is called after the user has changed the value by typing into the field.

Move the code which reads the value inside the function.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
  • I tried putting value code into validate function but the if conditions don't work. I mean now even if the player name is less then 6 letters it starts the game and user doesn't get an error. – masih Apr 07 '22 at 13:19