![](/img/trans.png)
[英]Error Message Overlap while creating a Sign Up form using JavaScript
[英]Is there a way to add an error message to show up on webpage using Javascript?
我正在嘗試在 Javascript 中添加錯誤消息處理,但遇到了問題。 如果用戶輸入的狀態長度不是兩個字符,我試圖讓它輸出錯誤消息。 如果有幫助,我也包括我的 renderBarChart 函數。
js
stateSubmitButton.addEventListener("click", function(event) {
event.preventDefault();
state = stateUserInput.value.toUpperCase();
let stateFeedbackElem = document.querySelector("#stateFeedback");
if (state.length == 2) {
stateUserInput.setCustomValidity("");
stateFeedbackElem.textContent = "";
renderBarChart(state);
state = "";
} else {
stateUserInput.setCustomValidity("Please enter a two letter abbreviated state.");
stateFeedbackElem.textContent = "Please enter a two letter abbreviated state.";
state = "";
}
})
html
<form class="form" novalidate>
<label for="state-input">State:</label>
<input name="state" type="text" id="state-input" placeholder="(i.e. WA)">
<button type="submit" id="state-submit" class="btn btn-dark btn-lg ml-2">Submit</button>
<div id="stateFeedback" class="invalid-feedback"></div>
</form>
我注意到幾個問題。
您在表單上設置了novalidate
,這意味着不會顯示.setCustomValidity()
錯誤,因為不會執行驗證。
如果在
<form>
元素上設置了novalidate
屬性,則不會發生約束的交互式驗證。-- 約束驗證
如果stateUserInput
是#state-input
輸入,則.textContent
應該可以工作,並且應該設置文本。 但它可能不會顯示,因為invalid-feedback
類具有 CSS 屬性display: none;
. 您需要添加d-block
類或使用invalid-feedback
元素,如 Bootstrap 示例中所示。
並且只是一個說明,更喜歡在表單上添加一個事件偵聽器並偵聽SubmitEvent而不是提交按鈕上的click
事件。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.