-2
我想更改瀏覽器中輸入的默認錯誤消息。我打開所有默認消息,創建帶有文本的隱藏div,並且我想爲每個無效輸入顯示此div。 div內的文本是不同的,對於一些輸入,我不需要文本錯誤。getElementsByClassName.style未定義
我的HTML表單:
<form id="registration__form" action="form_handler.php" class="form" method="POST" name="form">
<div>
<label for="email">email</label>
</div>
<div>
<input id="email" type="email" name="email" required="required">
<div class="error-message-2">error 1</div>
</div>
<div>
<label for="number">number</label>
</div>
<div>
<input id="number" type="text" name="number" required="required">
<div class="error-message-2">error 2</div>
</div>
<div>
<label for="company">company</label>
</div>
<div>
<input id="company" type="text" name="company" required="required">
</div>
<div>
company
</div>
<div>
<input type="password" id="field" data-indicator="pwindicator" name="password" required="required">
</div>
<div>
<div id="pwindicator" class="pwindicator">
<div class="bar">
</div>
<div class="label"></div>
</div>
</div>
我的CSS是非常簡單的
.error-message-2 {
display: none;
color: #fd1d1e;
}
我的JS
function replaceValidationUI(form) {
// Suppress the default bubbles
form.addEventListener("invalid", function(event) {
event.preventDefault();
}, true);
// Support Safari, iOS Safari, and the Android browser—each of which do not prevent
// form submissions by default
form.addEventListener("submit", function(event) {
if (!this.checkValidity()) {
event.preventDefault();
}
});
var submitButton = form.querySelector("button:not([type=button]), input[type=submit]");
submitButton.addEventListener("click", function(event) {
var invalidFields = form.querySelectorAll(":invalid"),
errorMessages = form.querySelectorAll(".error-message"),
parent;
// Remove any existing messages
for (var i = 0; i < errorMessages.length; i++) {
errorMessages[i].parentNode.removeChild(errorMessages[i]);
}
for (var i = 0; i < invalidFields.length; i++) {
parent = invalidFields[i].parentNode;
parent.getElementsByClassName("error-message-2").style.display = "block";
}
// If there are errors, give focus to the first invalid field
if (invalidFields.length > 0) {
invalidFields[0].focus();
}
});
}
// Replace the validation UI for all forms
var forms = document.querySelectorAll("form");
for (var i = 0; i < forms.length; i++) {
replaceValidationUI(forms[i]);
}
我有錯誤 'getElementsByClassName.style未定義' 這裏
for (var i = 0; i < invalidFields.length; i++) {
parent = invalidFields[i].parentNode;
parent.getElementsByClassName("error-message-2").style.display = "block";
}
有什麼不對?
P.S. JSFiddle here