简体   繁体   中英

span inside input field and remove html text when i submit

I am new to php, I want my span to be displayed in the input field and after submitting the form, I hate this * required field and * continue to display.

<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>

在此输入图像描述

You can't place it inside the input.

You can use absolute positioning inside a container to place it on top of the input:

 .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> 

If you only want to show the error when there is one:

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

Here I assume the variable is an empty string when there is no error.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM