0

在 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";
  }
}
4

3 回答 3

0

尝试这个 :

function removeDummy() {
  var elem = document.getElementById('firstname');
  elem.parentNode.removeChild(elem);
}

参考这个:http ://www.w3schools.com/js/js_htmldom_nodes.asp

于 2014-05-15T12:26:10.687 回答
0

尝试这个 :

document.getElementById("my-element").remove();
OR 
document.getElementsByClassName("my-elements").remove();
于 2013-10-17T04:38:37.263 回答
0

替代方案 - 我建议不要使用 document.createElement() 通过 javascript 创建 DIV,而是将 DIV 的 HTML 放入带有 style="display:none;" 的页面中 最初隐藏它。给 div 一个 id,例如 id="errorDiv"。要显示错误消息时,请使用:

document.getElementById('errorDiv').style.display = 'block';

准备好隐藏消息时,请使用:

document.getElementById('errorDiv').style.display = 'none';
于 2013-10-17T04:02:21.120 回答