php - I want to get checkbox already checked when we retrieve data from database in edit form -
<?php $a=array('cricket','reading','travelling','swimming','badminton');$hb=explode(" ",$row['hobby']); ?> hobbies:<input type="checkbox" name="chk[]" value="cricket"<?php if(in_array('cricket',$hb)){echo 'checked="checked"'; }?> />cricket <input type="checkbox" name="chk[]" value="reading" <?php if(in_array('reading',$hb)) { echo 'checked="checked"'; }?> />reading <input type="checkbox" name="chk[]" value="travelling" <?php if(in_array('travelling',$hb)) { echo 'checked="checked"'; }?> />travelling <input type="checkbox" name="chk[]" value="swimming" <?php if(in_array('swimming',$hb)) { echo 'checked="checked"'; }?> />swimming <input type="checkbox" name="chk[]" value="badminton" <?php if(in_array('badminton',$hb)) { echo 'checked="checked"'; }?> />badminton
the following code complete trying do. have test case providing "row" data source. set options (which want data source well), iterate through options, validate in array, , add check field if required. shows clear distinction between html , php future developers review code.
<?php // test case $row['hobby'] = 'cricket travelling'; // logic $formhtml = ""; $options = array('cricket','reading','travelling','swimming','badminton'); $selectedhobbies = explode(" ",$row['hobby']); foreach($options $option){ $checked = (in_array($option, $selectedhobbies)) ? "checked=checked" : ""; $formhtml .= <<<html <input type="checkbox" name="chk[]" value="{$option}" {$checked} />{$option} html; } ?> <html> <head> </head> <body> hobbies: <?php echo $formhtml; ?> </body> </html>
Comments
Post a Comment