在drupal 7 forms api中的SelectForm控件中触发onchange事件

在drupal 7 forms api中的SelectForm控件中触发onchange事件,forms,drupal,drupal-7,form-api,form-control,Forms,Drupal,Drupal 7,Form Api,Form Control,我在Drupal7中有一个选择表单控件。如何在onchange事件触发时调用函数 这是我的选择表单控制代码: $form['id']['signature'] = array( '#type' => 'select', '#options' => array( 0 => t('Browse...'), 1 => t('Sign...'), 2 => t('Clear...'),

我在Drupal7中有一个选择表单控件。如何在onchange事件触发时调用函数

这是我的选择表单控制代码:

$form['id']['signature'] = array(
    '#type' => 'select',       
    '#options' => array(
        0 => t('Browse...'),
        1 => t('Sign...'),
        2 => t('Clear...'),        
    ),       
);

你可以用“attibutes”来做这件事。
例如

虽然我从不喜欢将事件属性添加到html标记中,但您也可以通过向表单中添加内联(或扩展)javascript来实现,其行为如下:

$form['id']['signature'] = array(
    '#type' => 'select',       
    '#options' => array(
        0 => t('Browse...'),
        1 => t('Sign...'),
        2 => t('Clear...'),        
    ),
    '#attributes' => array(
        'id' => array('signature-goes-here'),
    ),
);
$form['id']['signature']['#attached']['js'][] = array(
    'data' => "
Drupal.behaviors.signature = function (context) {
  $('#signature-goes-here', context).change(function () {
    // Do stuff here.
  });
}
",
    'type' => 'inline',
);
但是,如果您想在表单项发生变化时启动ajax,您可能会使用Drupal表单api功能

$form['id']['signature'] = array(
    '#type' => 'select',       
    '#options' => array(
        0 => t('Browse...'),
        1 => t('Sign...'),
        2 => t('Clear...'),        
    ),
    '#attributes' => array(
        'id' => array('signature-goes-here'),
    ),
);
$form['id']['signature']['#attached']['js'][] = array(
    'data' => "
Drupal.behaviors.signature = function (context) {
  $('#signature-goes-here', context).change(function () {
    // Do stuff here.
  });
}
",
    'type' => 'inline',
);