form.addEventListener('submit', (e) => { //create new invitee name
let text = input.value; //collect text value from input field
let counter = 0;
if (text != "") {
createLI(text); //executes function to add new invitee.
} else {. /*if text field is blank error message to be printed only once regardless on multiple entries with blank input*/
const errorText = document.getElementById('enterName');
const label = document.createElement('label');
label.textContent = "please enter your full name";
label.setAttribute("style", "color: red");
if (counter == 0) {
errorText.appendChild(label);
counter += 1;
}
}
});
最佳答案
您需要在函数外部声明计数器
,否则每次用户提交表单时都会重置它。
let counter = 0;
form.addEventListener('submit', (e) => { /* Your awesome eventhandler */ });
发生这种情况是因为 JavaScript 会在函数结束后删除您的变量,并在事件再次触发时重新声明它。所以它实际上重新初始化计数器
。
PROTIP:使用 bool
而不是 int
,这样您就可以
if (messageShowed) { /* Insert some code */ }
关于javascript - 如果输入字段为空并且用户使用空白输入按回车键,我只想打印一次消息。我哪里出错了,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50100456/