form提交時隱藏input發生的錯誤
問題描述
-
在form表單提交的時候,有些input標簽被隱藏,表單驗證過程中會出現
An invalid form control with name='' is not focusable
的錯誤 -
雖然我遇到的問題是我的input標簽根本沒有required屬性,但是在該標簽隱藏之前,(我的是使用tab欄切換)我輸入了錯誤的格式,再隱藏,這時候他其實是錯誤的,會被form表單同樣去驗證,但是由於它被隱藏,瀏覽器獲取不到焦點就會報錯。
解決方法
- 隱藏之前將該input的value值設置為空即可.我的input上面沒有使用required屬性。
如果input含有display:none
和required
屬性,也會產生該錯誤
- 產生原因
Chrome希望專注於需要但仍為空的控件,以便可以彈出消息“請填寫此字段”。但是,如果控件在Chrome想要彈出消息的時候隱藏,即在提交表單時,Chrome無法關注該控件,因為它是隱藏的,因此表單不會提交。
- 解決方法如下
- 隱藏時,將required屬性刪除
selector.removeAttribute("required")
-
沒有使用required的話,或許是由於button按鈕,類型未設置造成。設置
<button type="button">
-
form表單不驗證,即添加novalidate屬性。(不是最終解決辦法)
<form novalidate></form>
-
既然是由於使用了
display:none
造成,同樣的visibility: hidden
也會造成問題,那就不使用。通過可以設置css樣式opacity: 0;
-
禁用此表單控件。
disabled
這是因為通常如果你隱藏了表單控件,那是因為你不關心它的價值。所以這個表單控件名稱值對在提交表單時不會被發送。
$("body").on("submit", ".myForm", function(evt) {
// Disable things that we don't want to validate.
$(["input:hidden, textarea:hidden, select:hidden"]).attr("disabled", true);
// If HTML5 Validation is available let it run. Otherwise prevent default.
if (this.el.checkValidity && !this.el.checkValidity()) {
// Re-enable things that we previously disabled.
$(["input:hidden, textarea:hidden, select:hidden"]).attr("disabled", false);
return true;
}
evt.preventDefault();
// Re-enable things that we previously disabled.
$(["input:hidden, textarea:hidden, select:hidden"]).attr("disabled", false);
// Whatever other form processing stuff goes here.
});
如有其他更好方法,歡迎留言!
參考
https://stackoverflow.com/questions/22148080/an-invalid-form-control-with-name-is-not-focusable