I am having a problem in switching colors with PHP variables using css class. I want to change color of the text of an error message under a form box on a wrong form input. The initial color of the text of the form’s message is green, if it is an error than it should change the message text color into red without moving anything on the screen. Somehow it is not switching.
CSS:
.fcol { color: green; }
.ferr { color: red; }
HTML:
<form method="post" class="formbox" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" >
<div>
<label for="fname"> First Name</label> <br />
<input type="text" name="fname" value="<?php echo $fname;?>" required> <br />
<span style="font-size:14px" class="<?php echo $class; ?>" > <?php echo $nameErr;?> </span>
</div> <br />
<div> <input type="submit" name="submit" class="buttons" value="Submit"> </div>
</form>
PHP:
$class = "fcol";
$nameErr = "Only letters please!";
if ( $_SERVER[ "REQUEST_METHOD" ] == "POST" ) {
if ( empty( $_POST[ "fname" ] ) ) {
$nameErr = "Name is required";
} else {
$fname = cleanvar( $_POST[ "fname" ] );
if ( !preg_match( "/^[a-zA-Z ]*$/", $fname ) ) {
$class = "ferr"; /* Here I am having problem. This code being not read */
$nameErr = "Only letters please=> ";
}
}
}
function cleanvar( $userinput ) {
$inp = trim( $userinput );
$inp = stripslashes( $userinput );
$inp = htmlspecialchars( $userinput );
return $inp;
}
2
Answers
It works for me. Here’s my code, and I only added in the
$fname
default to blank value.I cleaned up the code and got it working on a local PHP Web server. The main change I made was to check if $fname is set and not empty in the form. I also edited some of the texts, which were incorrect, and removed the "required" attr from the name field for testing:
The code is below, and here is a link to a working version that doesn’t require submitting a form. Just change the $fname var at the top and execute:
https://onlinephp.io/c/e0759