Get checked and unchecked checkboxes value

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.

Answers:

Answer

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';
}
Answer

A checkbox will be sent to the server (when the form is submitted) only if it's checked, otherwise it's not submitted

also change

onclick="pickIt('1');" /
Answer

Two options:

  1. Make hidden fields per checkbox and set the value to 0 or 1 with javascript when you (un)check the checkbox. Then ignore the "on" values in your $_POST.
  2. Php must know how many (and which) checkboxes there are, so the $_POST values that are missing are unchecked boxes. You could do this with a for loop.

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.