Reputation: 1481
What I'm trying to do is change
<input name="username">
to something like
<input name="username" class="empty">
if the form is empty.
Here's the PHP I've got for it in a separate file:
$username = $_POST['username'];
if(empty($username)) {
// add HTML attribute to tag
}
How would I do this?
Upvotes: 0
Views: 1221
Reputation: 2229
<?php
if(isset($_POST['save_btn'])) {
$class = 'class="empty"';
}
?>
<form method="post" action="#">
<input name="username" <?php if (!empty( $class )){echo $class ;} ?> >
<input type="submit" name="save_btn" value="save">
</form>
Upvotes: 1
Reputation: 8334
Here is the solution that i suggest: After submiting the form ,in action.php you will check if username is empty,if it's empty , you will redirect to index.php page with a variable in the url that indicates if field is empty or not(you can also use sessions).
index.php page :
<?php
if (isset($_GET['empty'] )){$empty="class='empty'";}
else {
$empty="";
}
?>
<form method="post" action="action.php">
<input name="username" <?php echo $empty; ?> />
<input type="submit" name="submit" value="save" />
</form>
Your action.php page:
<?php
$username = $_POST['username'];
if(empty($username)) {
header('location:index.php?empty=1');
}
?>
Upvotes: 1
Reputation: 226
Is this in a form that sends to itself? Then try to use the PHP directly in the HTML like this
<input name="username" class=" <?=(empty($_POST['username'])?"empty":"";?> " />
by using a shortened if-statement the script checks for an empty username field and then outputs the string "empty" in the classes attribute.
Offtopic: use trim() to check if the field is really empty, and remove whitespace.
Upvotes: 0
Reputation: 7880
You can use echo
if the form doesn't already exist.
<?php
$username = $_POST['username'];
if(empty($username)) {
// add HTML attribute to tag
echo "<input name=\"username\" class=\"empty\">";
} else {
echo "<input name=\"username\">";
}
?>
Upvotes: 0