动态填充复选框


Dynamically populate checkboxes

简单的问题,我试图动态填充html表单复选框,但当我试图通过使用html中复选框的checked属性来实现这一点时,它无法正常工作。无论我使用checked='0' / checked='1'checked='true' / checked='false'还是checked='checked' / checked='unchecked',复选框都保持选中状态。

尽管我通过在php中应用额外的检查解决了这个问题,如下所示。。。

while($contact = $db->fetchByAssoc($contacts))
{
$include_checked =( $contact['include'])? " checked={$contact['include']} ": "";
$opted_checked = ($contact['opted_out'])? " checked={$contact['include']} ": "";
$html.="<tr><td>{$contact['name']} </td>
            <td><input type='checkbox' {$include_checked}/> </td>    
            <td><input type='checkbox' {$opted_checked}/> </td>

有更好的解决方案吗???

使用yes预先选择它。删除它以在默认情况下取消选中

<input type="checkbox" checked="yes"/>

或`checked="checked"

<input type="checkbox" checked="checked"/>

或者,但已弃用且不鼓励使用:

<input type="checkbox" checked />

未选中?根本不要使用任何选项。只需删除它。通过后端无法不选择它。当然,这根本不需要。

checked属性的值无关紧要。如果要取消选中checked属性,则根本不要设置该属性。

<input type="checkbox" />