Jump to content

[SOLVED] multiple checkboxes checked on reload


xpace

Recommended Posts

Hi all,

 

I have this code, created myself

<?php
$xbox = array(1,2,3,4,5); //this will be take from database - this is just for testing
reset($xbox);

if($_POST){
foreach($_POST['box'] as $key=>$value){
$_SESSION['storedbox'][$key] = $value;
}

foreach($_SESSION['storedbox'] as $key=>$value){
echo 'The value of $_SESSION['."'".$key."'".'] is '."'".$value."'".' <br />'; //just for testing
}
}
echo "<form action='' method='POST'>";

if(isset($_SESSION['storedbox'])){	

foreach($xbox as $x){

	for($i=0;$i<count($_SESSION['storedbox']);$i++){

		if($_SESSION['storedbox'][$i] == $x){
		  	$x_sel = "CHECKED";
		}else{
			$x_sel = NULL;
		}	
		echo "box_".$x." <input type='checkbox' name='box[]' value='".$x."' ".$x_sel."><br />";	

	}
}

}else{

	foreach($xbox as $x){

		echo "box_".$x." <input type='checkbox' name='box[]' value='".$x."' ".$x_sel."><br />";	

	}
}

echo "<input type = 'submit' name='go' value=' go '></form>";




?>

 

and the purpose is that when you select something and hit GO button it should reappeared exactly how you selected it in the first place.

it's ok when you select only one checkbox but when you do multiple it will multiply the checkboxes as well.

you can try for yourself.

I have no idea where the problem is though I know there is something I don't like in the code but not sure where :)

 

thanks a lot

hey,

 

I know I do, because I can see it on a page but I don't know which area to take out or move somewhere else- that's the part where I said that I have no idea where the problem is :)

 

if you could just point me there that would really help

 

thanks

You're making it too complicated:

 

<?php
$xbox = array(1,2,3,4,5); //this will be take from database - this is just for testing
reset($xbox);

if($_POST['box']){
    //Saved the submitted values to session variable
    $_SESSION['storedbox'] = $_POST['box'];

    foreach($_SESSION['storedbox'] as $key => $value){
        echo "The value of \$_SESSION['{$key}'] is {$value}<br />\n"; //just for testing
    }
}

//Create the form
echo "<form action=\"\" method=\"POST\">\n";
foreach($xbox as $x){

    if (isset($_SESSION['storedbox']) && is_array($_SESSION['storedbox'])) {
        //Set the checked state for each option
        $checked =  (in_array($x, $_SESSION['storedbox'])) ? ' checked="checked"' :'';
    }
    //Display label and checkbox
    echo "box_{$x}<input type=\"checkbox\" name=\"box[]\" value=\"{$x}\"{$checked} /><br />\n";
}
echo "<button type=\"submit\"> go </button></form>";

?>

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.