0

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?

4
  • Has the tag already been outputted? Commented Aug 19, 2013 at 1:14
  • 2
    check this out php.net/manual/en/domelement.setattribute.php Commented Aug 19, 2013 at 1:15
  • 1
    Like does it already exist or are you creating the tag from scratch? Commented Aug 19, 2013 at 1:19
  • I would suggest moving that portion of the HTML to where your PHP logic is. Commented Aug 19, 2013 at 2:17

4 Answers 4

1

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');
     }
    ?>
Sign up to request clarification or add additional context in comments.

Comments

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

2 Comments

Makes sense, but that's kinda a lot of "empty"s in one statement. :)
I agree, its too ugly. Updated!
0

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\">";
}

?>

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.