Tuesday, October 18, 2016

HTML Checkbox Acts Unexpectedly When a Form is Edited

A fun filled masochistic exercises in programing is trying to figure out why an obvious piece of code fails. I had an HTML form for editing records. The form contained a checkbox for identifying whether the record is "active" or "inactive".

Pressing the submit button sends the edited data to the server, the edited data is then re-displayed on the form. Surprisingly the changes to the checkbox were not re-displayed correctly. Leaving me to wonder why.

The PHP code for the HTML form is shown below.

echo "Active:";
    if ($active=="Yes")
        { echo ' Unchecked if not active.';
            } else {
          echo ' Check to make active.';}


The PHP code evaluated by the server shown below.

if (!isset($_REQUEST['idavar']))
    {echo "An Error Occurred #9";
            } else {

My initial belief was that the HTML form when executed would send either a "0" or a "1" to the server since a checkbox is a boolean variable. Turned out, after much experimentation, not to be the case.

Even though the checkbox is a boolean variable it does not send the results to the server in the expected manner as either a "0" or as a "1". If "false" (the checkbox when not checked and the value is the number 0), no value is sent to the server and you get an error message ("An Error Occurred #9").

After some testing the following solution was developed. The checkbox in the form now correctly displays changes after the submit button is pressed.

The revised PHP code on the server is below.

if (!isset($_REQUEST['idavar']))
        $active =0;
            } else {
        $active =1;

No comments: