在 javascript 中,我有一个元素 div,当 HTML 表单中出现错误时会弹出。问题是在 HTML 表单中按下重置按钮后元素并没有消失。我希望它在按下重置按钮时消失,并且仅在表单中出现错误时出现,即没有字段输入。HTML 表单:
<form id="contact" action="" onsubmit="checkContactForm( this ); return false;">
<p>Fill in the form below to send me a message!</p>
<p>
<label for="firstname">First name:</label>
<input name="firstname" id="firstname" onfocus="resetField( this );" />
</p>
<p>
<label for="lastname">Last name:</label>
<input name="lastname" id="lastname" onfocus="resetField( this );" />
</p>
<p>
<label for="email">E-mail address:</label>
<input name="email" id="email" onfocus="resetField( this );" />
</p>
<p>
<label for="message">Your Message:</label>
<textarea name="message" id="message" onfocus="resetField( this );"></textarea>
</p>
<p>
<button type="submit">Send Message</button>
<button type="reset">Reset Form</button>
</p>
</form>
Javascript:
function checkContactForm( theForm ) {
for ( i in requiredFields ) {
var fieldName = requiredFields[ i ];
var theField = theForm[ fieldName ];
if ( !theField.value || theField.value == "Error" ) {
theField.style.color = "#f66";
theField.value = "Error";
var emptyFields = true;
}
if (!emptyFields) {
theForm.submit();
}
else
{
var div = document.createElement ("div");
div.id = "div";
div.style.width = "400px";
div.style.height = "20px";
div.style.position = "absolute";
div.style.marginTop = "-550px";
div.style.marginLeft = "160px";
div.style.fontStyle = "italic";
div.style.padding = "10px 20px 10px 10px";
div.style.background = "#D4D4D4";
div.style.borderStyle = "Solid";
div.style.borderColor = "#ff6666";
div.style.boxShadow = "0px 2px 10px 0px";
div.innerHTML = "Please fill in all fields before submitting the form";
document.body.appendChild(div);
/*$(div).fadeOut(5000);*/
}
if ( ) {
div.parentNode.removeChild ("div");
}
}
}
function resetField( theField ) {
if ( theField.value == "Error" || theField.value =="" ) {
theField.value = "";
theField.style.color = "#000";
}
}