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

问题描述 投票:-1回答:2

所以我有一个用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>

和“清除表单”按钮的代码

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

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

请帮忙

php forms reset
2个回答
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>

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>
最新问题
© www.soinside.com 2019 - 2024. All rights reserved.