单击按钮后显示错误 Javascript

Show error after button click Javascript

点击按钮后,我会检查我的文本字段是否为空。我的支票有效,但如果我显示我的消息,它会显示几秒钟。可能是我点击按钮的持续时间。这是我试过的一些代码。

<form>
    <div id="errorblock">
        <p id="errortext">Error.</p>
    </div>
    <!-- here are my input fields-->

    <button>Send</button>
</form>

这是我在页面初始化后添加事件监听器的地方:

document.getElementsByTagName("button")[0].addEventListener("click", function(){
    sendEmail();
});

function sendEmail() {

    //check if all fields are fill in. If not do this code;
    document.getElementById("errortext").innerHTML = "Fill in all the fields please.";

    var errorblock = document.getElementById("errorblock");       
    errorblock.style.visibility = "visible";
    errorblock.style.height = "46px";
}

谁能帮帮我? 谢谢

默认情况下 HTMLButtonElementtype="submit"。这意味着在按钮上单击表单已提交。您需要确保在表单出现错误时阻止此提交。例如通过调用事件对象的 preventDefault 方法:

document.getElementsByTagName("button")[0].addEventListener("click", function (e) {
    if (!sendEmail()) {
        e.preventDefault();
    }
});

function sendEmail() {

    //check if all fields are fill in. If not do this code;
    document.getElementById("errortext").innerHTML = "Fill in all the fields please.";

    var errorblock = document.getElementById("errorblock");
    errorblock.style.visibility = "visible";
    errorblock.style.height = "46px";

    // if there are errors return false
    // return true if input is correct
    return false;
}

我还建议在表单上监听 onsubmit 事件而不是按钮点击事件:

document.querySelector("form").addEventListener("submit", function (e) {
    if (!sendEmail()) {
        e.preventDefault();
    }
});