Alei
Alei

Reputation: 51

How do I make check appear in an edit form?

Basically I have a form that I start out with. On that form is the option to select a checkbox and once I click submit on that form, the information is read into a database and the condition on whether the checkbox has been selected now displays a '0' or '1' in the database.

Now I have an edit form. I choose the row I want to edit and my edit form gets populated with what is in the row. The only thing that doesn't show up, is whether that row was 'checked' on the first form. I want the checkbox to be marked if the user checked the checkbox on the first form and visversa.

Sorry if this sounds like a terrible explination.

Code for the first form:

<form method="post" action="processForm.php">

    Name: <input type="text" name="names" required = "required"><br>

    Activate: <input type="checkbox" name="activateBox"><br>

    <input type="submit" value="Create Users"><br>
</form>

And code for edit form:

<form method="post" action="editForm.php">

    ID: <input type="text" readonly name="id" value="<?php echo $row['id']; ?>"><br><br>
    First Name: <input type="text" name="firstName" value="<?php echo $row['firstName']; ?>"><br><br>
    Last Name: <input type="text" name="lastName" value="<?php echo $row['lastName']; ?>"><br><br>
    Email: <input type="text" name="email" value="<?php echo $row['email']; ?>"><br><br>
    Activate: <input type="checkbox" name="activateBox" value="<?php echo $row['activated']; ?>"><br><br>

    <input type="submit" value="Update"><br>

</form>

I tried doing this but it did nothing. I'm sure I'm missing something pretty simple but I can't figure out what.

if (isset($_POST['activateBox'])) {
    echo 'checked="checked"';
}

Upvotes: 1

Views: 207

Answers (2)

Activate: 
<input type="checkbox" name="activateBox"
<?php 
if($row['activated']==1){
  echo ' value="1" checked'; 
}else{
 echo ' value="0";
?>
<br><br>

Upvotes: 1

Asaph
Asaph

Reputation: 162831

The checked attribute of the <input type="checkbox"> tag should work. Most likely, when you loaded the edit form, it was an HTTP GET request, rather than a POST, so the $_POST['activateBox'] was empty.

In any case, reading the current state on an edit form from the client seems wrong. Shouldn't the current state come from the database?

Try this:

Activate: <input type="checkbox" name="activateBox"<?php if ($row['activated']) echo " checked"; ?>>

Upvotes: 3

Related Questions