0

I need to add a JavaScript code to my custom module, to modify the property in a date popup calendar and make it dynamic.

According to the documentation of the date popup calendar, the syntax for modifying the MaxDate is:

$( ".selector" ).datepicker({
  maxDate: "+1m"
});

I have to write "+1m" dynamically because it may be "+2m", "+3m", etc, it is variable.

How can I write a JavaScript code in my custom module and effect the popup calendar? I am wondering if I use script tag and put the JavaScript code inside it. In case, how can I do it by js?

1

You can attach a script to a form using the form's #attached attribute. You can do this in hook_form_alter as follows:

function hook_form_alter(&$form, &$form_state, $form_id)
{
  if($form_id == 'targeted_form')
  {
    $form['#attached']['js'][] = array
    (
      'type' => 'file',
      'data' => drupal_get_path('module', 'my_module') . '/scripts.js',
    );
  }
}

If you need to pass values from PHP to the form, you can attach values using Drupal.settings:

function hook_form_alter(&$form, &$form_state, $form_id)
{
  if($form_id == 'targeted_form')
  {
    $form['#attached']['js'][] = array
    (
      'type' => 'setting',
      'data' => array('myModule' => array('someSetting' => 'some value')),
    );
  }
}

Now the value will be available in your form at:

Drupal.settings.myModule.someSetting

Combine these two techniques to attach a form and pass it some settings.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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