vijay kumar
vijay kumar

Reputation: 377

how to show the previously checked checkbox using php

How to show the previously selected checkbox checked. in my table the values are storing like Refrigerator, Airconditioner, Television in one column

 <?php
    $answered="Refrigerator, Airconditioner, Television";
    $answer_options=array("Refrigerator","Airconditioner","tv");
    $ans_checked=explode(',',$answered);
    echo "<pre>";
    //print_r($ans_checked);
        $checked='';

    foreach($answer_options as $a)
    {
        echo $a."<br>";
        //print_r($ans_checked);
        if(in_array($a,$ans_checked))
        {
            $checked="checked";
        }
    //echo "$a<br>";
    echo "<input type='checkbox' ".$checked." >$a<br>";
    }
    ?>

Upvotes: 0

Views: 100

Answers (2)

Ravindra Singh
Ravindra Singh

Reputation: 56

<?php
    $answered="Refrigerator, Airconditioner, Television";
    $answered=str_replace(', ',',',$answered);
    $answer_options=array("Refrigerator","Airconditioner","tv");
    $ans_checked = explode(',', $answered);
    foreach ($answer_options as $a)
    {
        $checked = '';
        if (in_array($a, $ans_checked))
        {
            $checked = "checked";
        }
        echo $checked."<input type='checkbox' " . $checked . " >$a<br>";
    }
    ?>

Upvotes: 0

Sougata Bose
Sougata Bose

Reputation: 31749

As I see it is checking all the checkboxes for this code. Once the $checked is set with "checked" value it remains.

You should use else part to unset it if not present. Or do -

$checked='';
if(in_array($a,$ans_checked))
{
     $checked="checked";
}

inside the loop.

Also you should do -

$ans_checked=array_map('trim', explode(',',$answered));

Upvotes: 1

Related Questions