Home  »  ArticlesGuidesProgrammingTechnology   »   How to Know if the Checkbox is Checked When Form is Submitted to PHP

How to Know if the Checkbox is Checked When Form is Submitted to PHP

It may or may not surprise you to hear that a lot of newbie web developers grapple with how to handle the HTML form checkbox on the server backend.

The checkbox input actually works in two different ways as opposed to other inputs you find in HTML forms. The checkbox actually holds a boolean state as well as the outright string or numeric value depending on how the input is crafted.

It so happens most web developers when starting out get to know that the checkbox is used in a situation when a boolean suffices. The problem escalates when they need to send out the state of the checkbox back to the server.

Unfortunately, the server-side scripts are not able to read this information as it is not passed to the server as part of the request.

One way is to use JavaScript to check the state of the checkbox and then pass a value via GET or POST requests based on that. You can see more about passing GET and POST values here.

There is a more straightforward and native way to do it without JavaScript. It all depends on the attributes you attach to the checkbox. All you need to do is add this code as the checkbox:

<input name="val" type="checkbox" value="value" />

Then on the server, you need to catch the value with something as basic as this:

 isset($_POST['test']) {
 // do something useful based on the presence of the input
 }

or to be more precise, and a safer method

 if ($_POST['test'] == 'value1') {
 // do something useful based on the value of the input
 }

There you have it. You no longer need to grapple with handling the values from the checkbox.

Found this article interesting? Follow Brightwhiz on Facebook, Twitter, and YouTube to read and watch more content we post.