Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to get the unchecked value from checkbox?

Tags:

checkbox

php

i got a list of checkbox, when i checked the checkbox, it should insert the value into database. when i unchecked the checkbox then it should be delete data from database.

if i assign a value in checkbox then i only can get the checked checkbox value. if i using a hidden field then i can get all value of checkbox but then i dunno which 1 is check and which 1 is uncheck.

Anyone can help?

    $num="3";  
    for($i=1;$i<10;$i++){
    ?>
    <form name="form1" method="post" action="testcheckbox.php"> 
        <input type="hidden" name="task" value="validatesn">
        <input type="hidden" name="validate[]" value="<?php echo $i;?>">
        <input type="checkbox" name="validate[]" <?php if($num==$i){ echo "checked=checked";} ?> />Serialno<?php echo $i."<br/>"; ?>
    <?php
        $i++;
    }   
    ?>
        <input type="submit" name="submit" value="Validate" />
    </form>

    <?php
    if($_REQUEST['task'] == 'validatesn'){
       $valid=$_POST['validate'];
       foreach($valid as $v){
           echo $v;  //show all checkbox values
           //if checkbox= checked then insert value into database
           //if untick the checked checkbox then delete data from database
    }
  }
?>
like image 308
user367856 Avatar asked Jan 17 '23 03:01

user367856


1 Answers

The markup for a checkbox looks like so:

<input type="checkbox" value="myvalue" name="validate[]">

When you POST the form, you will see an array called validate in $_POST.

If that array is empty, then the checkbox was not checked. If that array contains "myvalue", then the checkbox was checked.

If you are dealing with multiple checkboxes like this:

<input type="checkbox" value="myvalue1" name="validate[]">
<input type="checkbox" value="myvalue2" name="validate[]">

Your script will need to know that the validate array in $_POST can contain values of myvalue1 and myvalue2. Then you can look into $_POST['validate'], and if the value exists in the array, then that checkbox was checked. You can use array_diff() to easily do this without writing any loops.

like image 161
F21 Avatar answered Jan 25 '23 05:01

F21