Drupal 7: Make select box autosubmit on change.

Published by Lennart Van Vaerenbergh on February 9, 2017

If you want your Drupal form to autosubmit when a select box's value changes, here's how the form render array looks like:
 
/**
 * Form callback; Builds a custom form.
 */
function my_module_custom_form($form, &$form_state) {
  $form['my_select_box'] = array(
    '#type' => 'select',
    '#title' => t('Select a value'),
    '#options' => array(
      t('Option 1'),
      t('Option 2'),
    ),
    '#attributes'     => array(
      'onChange' => 'this.form.submit();',
    ),
  );

  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Submit'),
    '#attributes' => array(
      'class' => array('js-hide'),
    ),
  );

  return $form;
}

By adding the "js-hide" class to the submit button, it will be hidden when javascript is enabled in the browser and shown when not.

Add new comment

(If you're a human, don't change the following field)
Your first name.
(If you're a human, don't change the following field)
Your first name.
CAPTCHA
This challenge is for testing whether or not you are a human visitor and to prevent automated spam submissions.