AJAX Example: Textfields driven by checkboxes

In this example, we just use checkboxes to determine whether textboxes are displayed.

One of the fundamental ideas of having a form change based on selections within the form is that the form is reconfiguring itself based on $form_state. So here, the generation of the form is driven by $form_state['values']. If the checkbox for last name is checked, then we generate a textfield for last name.

(Experiment with this one at http://d7.drupalexamples.info/examples/ajax_example/autotextfields or see the current code at http://api.drupal.org/api/function/ajax_example_autotextfields/7.)

/**
* Show/hide textfields based on AJAX-enabled checkbox clicks.
*/
function ajax_example_autotextfields($form, &$form_state) {

$form['ask_first_name'] = array(
'#type' => 'checkbox',
'#title' => t('Ask me my first name'),
'#ajax' => array(
'callback' => 'ajax_example_autotextfields_callback',
'wrapper' => 'textfields',
'effect' => 'fade',
)
);
$form['ask_last_name'] = array(
'#type' => 'checkbox',
'#title' => t('Ask me my last name'),
'#ajax' => array(
'callback' => 'ajax_example_autotextfields_callback',
'wrapper' => 'textfields',
'effect' => 'fade',

),
);

$form['textfields'] = array(
'#title' => t("Generated text fields for first and last name"),
'#prefix' => '

',
'#suffix' => '

',
'#type' => 'fieldset',
'#description' => t('This is where we put automatically generated textfields'),
);

if (!empty($form_state['values']['ask_first_name']) && $form_state['values']['ask_first_name']) {
$form['textfields']['first_name'] = array(
'#type' => 'textfield',
'#title' => t('First Name'),
);
}
if (!empty($form_state['values']['ask_last_name']) && $form_state['values']['ask_last_name']) {
$form['textfields']['last_name'] = array(
'#type' => 'textfield',
'#title' => t('Last Name'),
);
}

$form['submit'] = array(
'#type' => 'submit',
'#value' => t('Click Me'),
);

return $form;
}

/**
* Selects the piece of the form we want to use as replacement text and returns
* it as a form (renderable array).
*
* @return renderable array (the textfields element)
*/
function ajax_example_autotextfields_callback($form, $form_state) {
return $form['textfields'];
}

?>

Pages

Where to find me

Email me, randy at randyfay.com, Find me on ddev.com, Drupal.org and Slack: rfay, Facebook: randyfay, Hobobiker.com: The story of our 2 1/2 year bike trip.

Updated 2025-12-03