check select box when value = one of other value
I have a value like this :
$brands = "1,2,3,4,5"
and I have this :
<input type="checkbox" name="brand[]" value="<?php print"$brand_id"; ?>" /><?php print"$brand_id"; ?>
I want to write source so when $brand_id
is one of $bran开发者_如何转开发ds
check box checked means print "checked";
$brands is Variable and write by php
This will output an <input>
for every brand you have and append checked="checked"
to any of the selected.
$selected = array(2, 5);
$brands = array(1, 2, 3, 4, 5);
foreach ($brands as $brand) {
echo '<input type="checkbox" name="brand[]" value="'.$brand.'"'.(in_array($brand, $selected) ? ' checked="checked"' : '').'/>'."\n";
}
If the $brands and $selected are dynamic (for example from a MySQL database) you could do something like:
$brands = mysql_fetch_row('SELECT id FROM brand');
$selected = mysql_fetch_row("SELECT brand_id FROM user_brands WHERE user_id = '42'");
But without knowing more about your application, I cannot give a complete answer.
$brands =array("1,2,3,4,5");
<?php foreach($brand as $value){ ?>
<input type="checkbox" name="brand[]" value="<?php echo "$brand_id"; ?>"<?php ($brand_id==$value)?"checked":'';} />
<?php } ?>
<input type="checkbox" name="brand[]" value="<?php echo $brand_id.'" '; echo (in_array($brand_id, $brands))?"checked/>":"/>"; ?>
精彩评论