如何在Drupal7中正确地将onchange属性添加到表单字段中

How do I properly add an onchange attribute to a form field in Drupal 7

本文关键字:添加 属性 字段 表单 onchange Drupal7 正确地      更新时间:2023-09-26

在我正在编码的模块中,我有以下代码:

        'SelectType' => array(
          '#type' => 'select',
          '#name' => 'dropdown',
          '#options' => drupal_map_assoc(array(
                        'Keyword-classic','Keyword-Encore','Reserves: Instructor',)),
          '#attributes' => array('id' => array('SelectType'),
                  'onchange' => "change_action('catalogsearch', this.selectedIndex)",
          ),
        ),

这就产生了这样的结果:

[...]
<select id="SelectType" 
    onchange="change_action(&#039;catalogsearch&#039;, this.selectedIndex)"
    name="dropdown" class="form-select">
[...]

我需要它来产生(在第三行输出'而不是';):

[...]
<select id="SelectType" style="float:left;" 
    onchange="change_action('catalogsearch', this.selectedIndex)"
    name="dropdown" class="form-select">
[...]

我需要改变什么才能让它发挥作用?

您可以尝试以下操作:

    'SelectType' => array(
      '#type' => 'select',
      '#name' => 'dropdown',
      '#options' => drupal_map_assoc(array(
                    'Keyword-classic','Keyword-Encore','Reserves: Instructor',)),
      '#attributes' => array('id' => array('SelectType'),
              'onchange' => 'change_action(''catalogsearch'', this.selectedIndex)',
      ),
    ),

顺便说一下,由于ID是唯一的,并且一个元素一次只能使用一个,所以应该使用'id' => 'SelectType'而不是'id' => array('SelectType')

编辑:

如果上面的代码不起作用,那么你可以使用jQuery,如下所示:

$("#SelectType").change(function() { 
    YOUR CODE.....
});

我刚刚找到了"Drupal"的方法。

步骤1,使用drupal_add_js:设置一个包含下拉列表的变量

drupal_add_js(array('mymodule' => array('varname' => 'catalogsearch')), 'setting');

步骤2,添加"onchange"行作为

'onchange' => 'change_action(Drupal.settings.mymodule.varname, this.selectedIndex)'

通过这样做,可以在不需要'通过主题系统的情况下传递变量。主题系统总是对属性值调用check_plain,因此'''总是转换为&#039;