php - 跨越输入字段并在我提交时删除 html 文本

标签 php html css

我是 php 新手,我希望我的跨度显示在输入字段中,提交表单后,我讨厌这个 * 必填字段并 * 继续显示。

<html>
<head>
<style>
.error {color: #FF0000;}
</style>
</head>
<body>  

<?php
<h2>PHP Form Validation Example</h2>
<p><span class="error">* required field</span></p>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">  
  Name: <input type="text" name="name" value="<?php echo $name;?>">
  <span class="error">* <?php echo $nameErr;?> </span>
  <br><br>
  E-mail: <input type="text" name="email" value="<?php echo $email;?>">
  <span class="error">* <?php echo $emailErr;?></span>
  <br><br>
  Website: <input type="text" name="website" value="<?php echo $website;?>">
  <span class="error"><?php echo $websiteErr;?></span>
  <br><br>
  Comment: <textarea name="comment" rows="5" cols="40"><?php echo $comment;?></textarea>
  <br><br>
  Gender:
  <input type="radio" name="gender" value="female" <?php if (isset($gender) && $gender==="female") {echo "checked";}?>>Female
  <input type="radio" name="gender" value="male" <?php if (isset($gender) && $gender==="male") {echo "checked";}?>>Male
  <input type="radio" name="gender" value="other" <?php if (isset($gender) && $gender==="other") {echo "checked";}?>>Other
  <span class="error">* <?php echo $genderErr;?></span>
  <br><br>
  <input type="submit" name="submit" value="Submit">  
</form>

</body>
</html>

enter image description here

最佳答案

你不能把它放在输入里面。

您可以在容器内使用绝对定位将其放置在输入的顶部:

.input-container {
    position: relative;
    display: inline-block;
}

.input-container .error {
    font-size: 14px;
    color: red;
    position: absolute;
    right: 5px;
    top: 5px;
    font-style: italic;
}

label {
    display: inline-block;
    margin-right: 15px; 
}

input[type="text"] {
    width: 300px;
    height: 40px;
    padding: 5px 15px;
}
<form method="post">
    <div class="field-container">
        <label for="name">Name *</label>
        <div class="input-container">
            <input id="name" type="text" name="name" value="" />
            <span class="error">* This field should not be empty</span>
        </div>
    </div>
    <!-- repeat for other fields -->
</form>

如果你只想在出现错误时显示:

<?php if (isset($_POST['name']) && strlen($nameErr) > 0): ?>
    <span class="error"><?php echo $nameErr; ?></span>
<?php endif; ?>

这里我假设变量在没有错误的情况下是一个空字符串。

关于php - 跨越输入字段并在我提交时删除 html 文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55130168/

相关文章:

php - 如何将 SQL 中的流派列表传输到单独的数据库

php - 如何在 Mac 上开始使用 Apache、MySQL 和(PHP、Perl、Python)?

php - 根除电子邮件地址的模式

javascript - Jquery对象不支持属性或方法 "values"

javascript - 记录点击事件和目标

html - CSS 命名约定 - 嵌套 CSS

css - 在社交引擎中使用自定义布局?

jquery - 4 col 在 Bootstrap 中滚动 一个一个滚动

javascript - 窗口内的 HTML 窗口

php - foreach 循环插入所有复选框(选中和未选中)