xajax and Checkbox

In one of the forms I work on, I need to set other form fields based on the value of a checkbox. The value this.checked was passed as  parameter to xajax function.

<input type="checkbox" name="checkbox1" id="checkbox1" value="Y" onClick="xajax_function(this.checked);" />

In xajax function, the value of the parameter is either true or empty value.

function xajax_function($data) {
    $obj = new xajaxResponse();
    $obj->assign("field1", "value", $data ? "true value" : "false value");
    return $obj;
}

The problem is, the value in field1 always display “true value” whether the box is checked or not!

It turns out that the true passed is a string! Not boolean! You need to compare $data and “true” (with quotes).

replace line 3 of above php code:

$obj->assign("field1", "value", ($data == "true") ? "true value" : "false value");

Now it works as intended.

Alternatively check with isset($data) to see if checkbox is checked.

To check the opposite value, ie checkbox is not checked, use !isset($data).

Note: do not use / pass this.value as parameter. The value will always be the value assigned to checkbox, in this case, always “Y”.

2 thoughts on “xajax and Checkbox

  1. westbeck Reply

    I am using xajax.getFormValues(form) to send form values to the server side.

    Before PHP 5.3.1 I could use
    if [$aFormValues[‘CheckBox’] == “true”) to test for set/unset

    In PHP 5.3.1 returns error when checkbox is unset

    I now have tested with isset() with

    if (isset($aFormValues[‘CheckBox’]) {
    $objResponse->alert(“Checkbox set”);
    } else {
    $objResponse->alert(“Checkbox unset”);
    }

    This also results in error!

    As my site is down since my site was upgrade to new PHP version I really need a way to get around this new behavior for checkboxes?

  2. Carlo Rothove Reply

    Hi, my english isnt the most effective but I imagine by regulary visits of your respective blog it is going to be much better in the next time. You possess a good wrting style that is easy to understand and can aids people like me to learn english. I will be now a regulary visitor of your blog.

Leave a Reply

Your email address will not be published. Required fields are marked *