1

Basically I can get the value that applies to when the box is ticked (= 1), but I can't get it to send the default value of 0 when not checked.

<input type="checkbox" name="post_friend" value="1">

I've searched around and someone suggested setting a hidden checkbox, but it's not working for me.

<input type="hidden" name="post_friend" value="0">
user2571547
  • 87
  • 1
  • 1
  • 9

5 Answers5

5

Could you not do something like this?

$checkbox = isset($_POST['post_friend']) ? $_POST['post_friend'] : 0 ;

So if the checkbox is checked, variable is 1. If not, variable assigned value of 0

Becs Carter
  • 1,250
  • 1
  • 12
  • 27
  • the problem with this, is that you may not know the names of the unchecked fields. I have a similar problem, on which, depending on user data, the checkboxes' id's can vary. I can know what checkboxes (their id's) are checked after submission, but i cannot know (directly) what other checkboxes were there and were unchecked, so i could not update them on DB. – DiegoDD Dec 30 '13 at 18:55
1

The original method which was given by the OP should work, however, the value may very well be different.

For example,

<input type="checkbox" name="post_friend" value="1">
<input type="hidden" name="post_friend" value="0">

In this case ["post_friend"] = 0.

However, in this example:

<input type="checkbox" checked="checked" name="post_friend" value="1">
<input type="hidden" name="post_friend" value="0">

Most browsers will send ["post_friend"] = "1,0". Multiple values to the same property will usually be concatenated in the http request.

For this you can use String.Contains to find the 1.

However, here, you should really assess whether your input should be a checkbox, or more suitably, radio input.

Kana Ki
  • 390
  • 2
  • 16
0

Try something like below

<div class="col-xs-5 drinkingLeft">
<input type="checkbox" name="beer" id="beer"class="require-one col-xs-1" value="0"/>
<input id='beerHidden'  type='hidden' value='0' name='beer'>   
<label for="beer" class="col-xs-10">Beer </label>
</div>


 $('#beer').on('change', function () {
this.value = this.checked ? 1 : 0;
 }).change();

$("#submit").click(function () {
if(document.getElementById("beer").checked){
document.getElementById('beerHidden').disabled = true;
}
});
Hello Universe
  • 3,248
  • 7
  • 50
  • 86
0

HTML

 <input type="checkbox" id="chkbox1">

Jquery

if( $("#chkbox1").is(':checked')){
            value = "True";
        }else{
            value= "False";
        }
Aravindh Gopi
  • 2,083
  • 28
  • 36
0

the only possible solution is :

<?php
    // if data is posted, set value to 1, else to 0
    $check_0 = isset($_POST['check'][0]) ? 1 : 0;
    $check_1 = isset($_POST['check'][1]) ? 1 : 0;
?>

If you want to check info on the same page then use JS and check NULL values...

Shailender Ahuja
  • 314
  • 1
  • 3
  • 10