如何清除回显到span标记的内容

时间:2018-03-02 20:08:41

标签: php forms reset

所以我有一个用PHP制作的表格的问题。我在span标记中回显错误消息,并且我想在单击“clear form”按钮

后清除该消息

这是我的php,用于在字段未填写

时确定错误消息
<script>
function clearForm(){
    document.getElementById("firstName").value = '';
    document.getElementById("email").value = '';
    document.getElementById("lastName").value = '';
    document.getElementById("subject").value = '';
    document.getElementById("message").value = '';
    document.getElementsByTagName("span").value = "";
}
</script>
      <?php
      $confirm= "";
      $firstName = $lastName = $Email = $Subject = $Message = '';
      if ($_SERVER['REQUEST_METHOD'] == "POST") {
        if (isset($_POST["firstName"]) && $_POST["firstName"]!=null) {$firstName = $_POST['firstName'];} else {
          $confirm ="Please fill it in";
        }
        if (isset($_POST["lastName"]) && $_POST["lastName"]!=null) {$lastName = $_POST['lastName'];} else {
          $confirm ="Please fill it in";
        }
        if (isset($_POST["Email"]) && $_POST["Email"]!=null) {$Email = $_POST['Email'];} else {
          $confirm ="Please fill it in";
        }
        if (isset($_POST["Subject"]) && $_POST["Subject"]!=null) {$Subject = $_POST['Subject'];} else {
          $confirm ="Please fill it in";
        }
        if (isset($_POST["Message"])&& $_POST["Message"]!=null) {$Message = $_POST['Message'];} else {
          $confirm ="Please fill it in";
        }
      }
      if (isset($_POST["Clearform"])) {
        $confirm= "";
      }

      ?>

这就是它在身体中的样子

<form name="contact" action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']);?>" method="POST">
<p>Your Name: <br>
<input type="text" name="firstName" id="firstName" value="<?php echo $firstName;?>"><span id="confirm"><?php echo $confirm; ?></span></p>
</form>

“Clear form”按钮的代码

<input class="button" type="button" name="Clearform" value="Clear Form" onclick="clearForm();"/>

所以我做了这个小函数,将变量$ confirm设置为无内容,但它不起作用。

请帮忙

2 个答案:

答案 0 :(得分:0)

问题在于clearForm()您不应该使用.value,而是可以使用innerHTMLinnerTexttextContent。要查看它们之间的区别check this link

function clearSpan() {
  let mySpan = document.getElementById('errorSpan');
  mySpan.innerText = '';
}
<span id="errorSpan">This is text to be cleared on button click</span>
<button onclick="clearSpan();">Clear</button>

答案 1 :(得分:0)

这应该可以解决问题。使用JQUERY .hide()隐藏错误。

$("#btn").on("click", function(){
  $("#errmsg").fadeOut("slow");
});
#errmsg{
color:red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="btn">Click to remove error.</button><br>
<span id="errmsg">Your error</span>