Search code examples
javascriptdrupal-7drupal-formsdrupal-render

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


In the module I am coding, I have this code:

        '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)",
          ),
        ),

This produces this result:

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

I need it to produce (outputting ' instead of ' on the third line) :

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

What do I need to change to get this to work?


Solution

  • I just found the "Drupal" way of doing this.

    Step 1, set a variable to contain dropdown by using drupal_add_js:

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

    Step 2, add the 'onchange' line as

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

    By doing this, the variable is passed without the need of ' to be passed through the theme system. The theme system always calls check_plain on attribute values, therefore ' or \' is always converted to &#039;.