elunap
elunap

Reputation: 841

Checkbox always "on" when sending to php

I have this checkbox in my html

<input name="cb" class="cmn-toggle cmn-toggle-round" type="checkbox">

What I understood about how checkbox worked, was that when "checked" if you isset the input then it would "exist", and if wasn't "checked" wouldn't, so I did this:

if(isset($_REQUEST['cb'])){
   //do something
}else{
  //do something else
}

The problem is that when sending the form, it always exist, doesn't matter if checked or not, I don't know how to really see if really checked, so what am I doing wrong?

Upvotes: 0

Views: 666

Answers (2)

Drone
Drone

Reputation: 1134

You can check like this

if(isset($_REQUEST['cb']) && $_REQUEST['cb']){ 

Upvotes: 1

pes502
pes502

Reputation: 1587

isset() determine if a variable is set and is not NULL. So in your case, the $_REQUEST['cb'] always exist, so isset() will be true. So if you have isset() in your condition, you need to add a check, if the value is true or false.

You need edit your condition to:

if($_REQUEST['cb']) { ...

or

if($_REQUEST['cb'] == true){ ...

and the best way is use isset with check above:

if( isset($_REQUEST['cb']) && $_REQUEST['cb'] == true ) { ...

Upvotes: 2

Related Questions