lundi 29 août 2016

PHP array checkbox issue, keep the 'right' boxes checked after submit

I am currently created a checkbox system based on each school in an array. Everything works fine except, that after submit, only the first checkboxes are checked. Example: I have 10 checkboxes, and check box number 4,5 and 6. After submit, box 1,2 and 3 are checked. I want box 4,5 and 6 to keep their selection after submit. Hope that you can imagine by problem.

<!--Start Checkbox system for schools-->
<form method="POST">
<?php
$q = "SELECT id, name FROM $school_table";  
$result = mysqli_query($con, $q);
    while(($row =  mysqli_fetch_array($result))) {
    //First line of <input>
    echo '<input type="checkbox" name="check_list[]" value="';  

    //Value of the input (school ID)
    echo $row['id'] .'"';                                       

    //Keep the box checked after submit. PROBLEM MIGHT BE HERE!!!
    if(isset($_POST['check_list'][$row['id']])){echo 'checked="checked"';} 

    //Echos the school name out after the checkbox. 
    echo '>' . $row['name'] . " <br> ";                         
    }
?>
<script language="javascript">
//Select all on/off function
function checkAll(bx) {
    var cbs = document.getElementsByTagName('input');
    for(var i=0; i < cbs.length; i++) {
            if(cbs[i].type == 'checkbox') {
            cbs[i].checked = bx.checked;
            }
    }
}
</script>
<!--Check all mark. Works with Javascript written above-->
<input type="checkbox" name="check_all" onclick="checkAll(this)" <?php if(isset($_POST['check_all'])){echo "checked";} ?>> Check all: On/Off
<input type="submit" name="submit" value="sort"> 
</form>
<!--End Checkbox system for schools-->

Image of the problem. Take a look

Hope you guys can help me out :)




Aucun commentaire:

Enregistrer un commentaire