SULTAN
SULTAN

Reputation: 1159

remember user checkbox after validation

In my form, I have several checkboxes that are populated from a db table.

The issue is, when the user submits the form and gets error, the form can not remember his checked boxes!

here is the code I am working on:

while($n = mysqli_fetch_assoc($q))
{
echo '<div class="checkBoxesList"><label for="'.$n['eName'].'">'.$n['eName'].'</label><input type="checkbox" name="'.$n['eName'].'" id="'.$n['eName'].'" value="'.$n['id'].'" <?php echo (isset($_POST[\''.$n['eName'].'\'])?\'checked="checked"\':\'\') ?> /></div>';
}

I guess I have a problem in the 2nd echo within the main echo but I couldn't go over it.

FYI, I used to get this working by hard-coding all the checkboxes in the form e.g.

<div class="checkBoxesList"><label for="firstAid">First Aid</label><input type="checkbox" name="firstAid" id="firstAid" value="1"  <?php echo (isset($_POST['firstAid'])?'checked="checked"':'') ?> /></div>

Your help is highly appreciated.

Upvotes: 0

Views: 47

Answers (2)

rakeshjain
rakeshjain

Reputation: 1761

Replace

echo '<div class="checkBoxesList"><label for="'.$n['eName'].'">'.$n['eName'].'</label><input type="checkbox" name="'.$n['eName'].'" id="'.$n['eName'].'" value="'.$n['id'].'" <?php echo (isset($_POST[\''.$n['eName'].'\'])?\'checked="checked"\':\'\') ?> /></div>';

with

if(isset($_POST[$n['eName']])) {
    echo '<div class="checkBoxesList"><label  for="'.$n['eName'].'">'.$n['eName'].'</label><input type="checkbox" name="'.$n['eName'].'" id="'.$n['eName'].'" value="'.$n['id'].'" checked="checked"/></div>';
}
else {
    echo '<div class="checkBoxesList"><label for="'.$n['eName'].'">'.$n['eName'].'</label><input type="checkbox" name="'.$n['eName'].'" id="'.$n['eName'].'" value="'.$n['id'].'" /></div>';
}

Upvotes: 0

va5ja
va5ja

Reputation: 473

Try like so:

while($n = mysqli_fetch_assoc($q))
{
 echo '<div class="checkBoxesList"><label for="'.$n['eName'].'">'.$n['eName'].'</label><input type="checkbox" name="'.$n['eName'].'" id="'.$n['eName'].'" value="'.$n['id'].'" '.(isset($_POST[$n['eName']]) ? 'checked="checked"' : '') .' /></div>';
}

Upvotes: 1

Related Questions