lafuente lafuente - 3 months ago 24
HTML Question

How to remove duplicated checkboxes

Please help me solve this issue.
I'm trying to populate checkboxes according to the information from the database which is working but the problem is that it is for some unknown reasons duplicating the checkboxes.

<li class="treeview">
<a href="#"><i class="fa fa-tachometer"></i> <span>Dashboard</span></a>
<ul class="treeview-menu">
<li style="padding-left: 5px;">
<a href="#"><i class="active fa fa-search"></i> <span>Searches</span> <i class="fa fa-angle-left pull-right"></i></a>
<ul class="treeview-menu">
<div id="checkbox-container">
<li style="padding-left: 10px;">
<input type="checkbox" id="selectAll" onclick='selectAll(this.checked)'/>
<span style="color: #fff;">SELECT ALL</span>
</li>
<?php foreach ($query as $search_row) { ?>
<?php foreach($checkSearch as $s) { ?>
<?php
$box = 0;
if($search_row->searchid == $s->idsearch){
$box = 1;
}
?>
<form method="post" id="the-dash">
<li style="padding-left: 10px;">
<input type="checkbox" id="searches" class="searchid" onclick="getSearchId()" value="<?php echo $search_row->searchid; ?>" name="searchName" <?php echo ($box == 1 ? 'checked' : ''); ?>>
<span id="searchname" style="color: #fff; "><?php echo $search_row->searchname; ?> <?php echo '<br>'; ?><span>
</li>
</form>
<?php } ?>
<?php } ?>
</div>
</ul>
</li>
</ul>
</li>

Answer

Try this

In your controller, store id in an array

$idsearchs = array();
foreach($checkSearch as $s) {
    $idsearchs[] = $s->idsearch;
}

in your view

<?php foreach ($query as $search_row) {
    $box = in_array($search_row->searchid, $idsearchs) ? 1 : 0;
?>
    <li style="padding-left: 10px;">
        <form method="post" id="the-dash">
            <input type="checkbox" id="searches" class="searchid" onclick="getSearchId()" value="<?php echo $search_row->searchid; ?>" name="searchName"  <?php echo ($box == 1) ? 'checked="checked"' : ''; ?>> 
            <span id="searchname" style="color: #fff; "><?php echo $search_row->searchname; ?> <?php echo '<br>'; ?><span>
        </form>
    </li>
<?php } ?>

You have done foreach with $query and in side foreach with $checkSearch, there for you are getting duplicate checkbox.