Reputation: 35
The min-length of input is not working properly in this code. Sometimes it works and sometimes it doesn't. Why is this? I tried to input 3 characters using the 'if' statement of JavaScript, but I want to make an error message appear in the input window of html if I input less than 3 characters. Why doesn't the attribute value of the html input tag work properly?
const numberOfPeople = document.querySelector(".number-of-people");
const previousWord = document.querySelector(".previous-word");
const inputWord = document.querySelector("#input-word");
const submitButton = document.querySelector("#submit-button");
let number = parseInt(prompt("How many people are participating in the game?"));
let word;
let flag = true;
let flag2 = true;
(function() {
while (flag) {
flag = false;
if(number) {
numberOfPeople.textContent = number;
const onClickSubmitButton = (e) => {
e.preventDefault();
word = inputWord.value;
if (inputWord.value.length < 3) {
alert("Please enter 3 characters.")
} else if ((previousWord.textContent === "") || (previousWord.textContent[previousWord.textContent.length - 1] === word[0])) {
previousWord.textContent = word;
inputWord.value = "";
inputWord.focus();
flag = true;
} else {
alert("GAME_OVER");
inputWord.value = "";
previousWord.textContent = "";
numberOfPeople.textContent = "";
number = null;
submitButton.removeEventListener("click", onClickSubmitButton);
return;
}
}
submitButton.addEventListener("click", onClickSubmitButton);
} else {
number = parseInt(prompt("Please enter a number."));
if (number && flag2) {
numberOfPeople.textContent = number;
flag = true;
flag2 = false;
}
}
}
})()
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>word-chain game</title>
<script src="js/word-chain_game.js" defer></script>
</head>
<body>
<div class="word-chain__wrapper">
<h4>number-of-people : <span class="number-of-people"></span></h4>
<h4>previous-word : <span class="previous-word"></span></h4>
<form>
<label for="input-word">enter a word</label>
<input name="input-word" id="input-word" type="text" required minlength="3" maxlength="3" placeholder="Please enter a word."> <!-- This code is not working properly. -->
<input id="submit-button" type="submit" value="input"></input>
</form>
<h4></h4>
</div>
</body>
</html>
Upvotes: 0
Views: 780
Reputation: 774
You can apply style on input based on the required
minlength
attribute or you can attach an invalid event handler on input.
input:invalid{
color:red;
border-color:red;
}
<input type="text" oninvalid="alert('Please enter atleast 3 charcater in name field');" required minlength="3">
Upvotes: 1