PHPRO.ORG

Xajax brings speed and simplicity to creating ajax functionality from with PHP. An problem that often arises is assigning the value of a checkbox to checked. This can be used to either set a default checked option, or in relation to another event.

Many times code arises trying to set the the checkbox to checked by assigning 'checked' or value='checked'. The key to producing the correct result is to remember how a checkbox is represented in the Document Object Model (DOM). The HTML DOM checked Property is defined as follows.

checkboxObject.checked=true|false

So, instead of setting the value to checked or checked to checked, the checked value must set to boolean true. In xajax this is done as follows.


<?php
    
/*** assign the checked value to true ***/
    
$objResponse->assign'checkbox_id''checked'true );
?>

Where checkbox_id is the unique identifier for the checkbox to be checked. Similarly, to uncheck a checkbox using xajax, the value is simply set to false.


<?php
        
/*** assign the checked value to true ***/
        
$objResponse->assign'checkbox_id''checked'false );
?>

In this following example, a simple group of animals is supplied with checkboxes, and an input text form is supplied into which the name of an animal can be typed. If an animal name is supplied in the checkbox when the form is submitted, the appropriate checkbox will be checked.


<?php
        
/*** some error reporting ***/
        
error_reportingE_ALL );

        
/*** include the xajax bootstrap ***/
        
include 'xajax/xajax_core/xajax.inc.php';

        
/*** a new xajax object ***/
        
$xajax = new xajax();

        
/*** register a PHP function with xajax ***/
        
$xajax->register(XAJAX_FUNCTION'clickme');

        
/*** process the request ***/
        
$xajax->processRequest();

        
/*** the path is relative to the web root mmmk ***/
        
$xajax_js $xajax->getJavascript('/xajax');

        function 
clickMe($form_values)
        {
                
$objResponse = new xajaxResponse;
                
$value strtolower$form_values['animal_text'] );
                
$objResponse->assign$value'checked'true );
                return 
$objResponse;
        }
?>

<html>
<head>
<title>PHPRO XajaX Checkbox</title>

<?php
        
echo $xajax_js;
?>
</head>

<body>

<form id="my_form" name="my_form" action="" method="post" onsubmit="xajax_clickme(xajax.getFormValues('my_form')); return false;">

<input type="checkbox" name="dingo" id="dingo" />Dingo<br />
<input type="checkbox" name="platypus" id="platypus" />Platypus<br />
<input type="checkbox" name="wombat" id="wombat" />Wombat<br />
<input type="checkbox" name="wallaby" id="wallaby" />Wallaby<br />
<input type="checkbox" name="kangaroo" id="kangaroo" />Kangaroo<br />

<input type="text" name="animal_text" /> Name<br />
<input type="submit" value="Click Me" />
</form>
</body>
</html>