Javascript – Get checked and unchecked checkboxes value

htmljavascriptmysqlphp

This is my script:

HTML Code:

<script>
function pickIt(pId){
    if(document.getElementById(pId).checked==true){
        document.getElementById(pId).checked=false;
    }else{
        document.getElementById(pId).checked = true;
    }
    submitForm();
    return true;
}
</script>
<img src="images/bagua-square.gif" border="0" usemap="#Map2" />
<map name="Map2" id="Map2">
    <area shape="rect" coords="201,14,284,100" onclick="pickIt(1);" />
    <area shape="rect" coords="202,104,284,190" onclick="pickIt(2);" />
    <area shape="rect" coords="202,195,284,283" onclick="pickIt(3);" />
</map>
<div style="display:none;">
    <input type="checkbox" id="1" name="box[]" />
    <input type="checkbox" id="2" name="box[]" />
    <input type="checkbox" id="3" name="box[]" />
</div>

PHP Code:

<?php
    print_r($_POST['box']);
?>

When I click on box id 1 pickIt() function turn checkbox 1 to on. And the php shows array(0=>'on')

But I also want to get checkbox value which are not checked such that php will show
array(0=>'on', 1=>'off', 2=>'off')

Actually i want to get all checkboxes with their status on and off because i am using these id in mysql db to update record status on or off.
please guide.

Best Solution

Checkboxes send their value if they are checked and are not sent at all if they are not.

You should have:

<input type="checkbox" id="1" name="box[]" value="1" />
<input type="checkbox" id="2" name="box[]" value="2"  />
<input type="checkbox" id="3" name="box[]" value="3"  />

So the values will be 1, 2 and 3 instead of on, on and on. Then you can tell which ones are checked as they won't all be the same.

If you really want your data structure to be array(0=>'on', 1=>'off', 2=>'off') then you could do:

$foo = array();
for ($i = 1; $i <= 3; $i++) {
    $foo[$i] = in_array($i, $_GET['box']) ? 'on' : 'off';
}