Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remember checkbox input in PHP Forms

For usability purposes I like to set up my form fields this way:

<?php

$username = $_POST['username'];
$message  = $_POST['message'];

?>

<input type="text" name="username" value="<?php echo $username; ?>" />

<textarea name="message"><?php echo $message; ?></textarea>

This way if the user fails validation, the form input he entered previously will still be there and there would be no need to start from scratch.

My problem is I can't seem to keep check boxes selected with the option that the user had chosen before (when the page refreshes after validation fails). How to do this?

like image 524
Derek Avatar asked Apr 28 '26 09:04

Derek


1 Answers

My first suggestion would be to use some client-side validation first. Maybe an AJAX call that performs the validation checks before continuing.

If that is not an option, then try this:

<input type="checkbox" name="subscribe" <?php echo (isset($_POST['subscribe'])?'checked="checked"':'') ?> />

So if subscribe is = 1, then it should select the box for you.

like image 82
St. John Johnson Avatar answered Apr 30 '26 00:04

St. John Johnson