I have a content-type "Document". I have a multiple select dropdown box in my form.

$form['priorities']['selectoffid'] = array(
    '#type' => 'select',
    '#title' => 'Select Signatories',
    '#id' => 'select-chosen',
    '#attributes' => array('multiple' => 'multiple', 'style' => 'width:100%'),

Each option of the dropdown corresponds to a textfield. Selected option's corresponding text field are shown and unselected option's corresponding text field are hidden.

enter image description here

Now everytime I hit the Save button and some other required form elements are not filled, it reloads and display the form errors. After reloading some text fields that are supposed to be visible is now hidden.

enter image description here

The value of the multiple select dropdown still consist of 3 values, according to the $form_state variable , but some of it's corresponding text fields are not visible anymore. How will I make it visible again? I tried using after_build form.

$form['#after_build'][] = 'document_monitoring_form_after_build';   

function document_monitoring_form_after_build($form, &$form_state){  

    drupal_add_js(drupal_get_path('module','document_monitoring') . '/myscript.js');

    return $form;       

In my myscript.js :

alert('Javascript is called');
document.getElmentById('priority-6').style.display = 'block';
document.getElmentById('priority-22').style.display = 'block';
document.getElmentById('priority-5').style.display = 'block';
alert('Javascript is called');  

The javascript is called before the multiple select dropdown is rendered. How will I make the javascript be called right after the form elements is rendered?

1 Answer 1


You need to wait for the DOM to be ready (i.e. when then browser has finished comprehending the HTML).

Drupal's javascript API provides a natural place for your code, in the form of a behavior, e.g.

(function($) {
  Drupal.behaviors.mymoduleFoo = {
    attach: function(context, settings) {
      // ...

The attach method is invoked when the DOM is ready, and also at other points in the page execution when something might have changed (e.g. when an AJAX call is made), to give you the opportunity to respond to any new/change elements that might affect your code's functionality.

  • Thank you, tried what you said in my javascript, but it seems '#after_build' is not the right event to trigger the javascript? Am I right? Jun 29, 2017 at 8:46
  • 1
    I wouldn't have thought it would make a difference, but best practice would probably be to use #attached in the form builder or form alter function itself
    – Clive
    Jun 29, 2017 at 8:59
  • #attached works together with the behaviors. Thanks. Jul 14, 2017 at 1:02

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.