1

I've been searching around how to add jQuery to Drupal 7, but i couldn't make it work. Here is my steps:

Step 1: I create a javascript file and put into my module under js directory.

Step 2: I added the file to my module .info

 scripts[] = js/xxx.js

Step 3: The contents of the xxx.js

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

    $("#edit-field_a",context).change(function(){
      currentValue = $(this).val();
      alert(currentValue); // no fire at all
      if(currentValue == 'a')
        {
            $('#edit-field_b').val('All');
        }
    }

}
};

})(jQuery);

All the fields are on exposed filter form. I wish to do something like the value of the field_b select list changed based on field_a select list.

What did i miss? Is my jQuery correct?

Updates: Previous js is wrong, corrected here.

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

    $("#edit-field_a",context).change(function(){
      currentValue = $(this).val();
      alert(currentValue); // no fire at all
      if(currentValue == 'a')
        {
            $('#edit-field_b').val('All');
        }
    });

}
}

})(jQuery);
  • Did you check if .js file is loaded, if yes did you see anything on the error console for any javascript error??, did you check if 'id' is there in the DOM or not ?? – prabeen giri Dec 26 '13 at 9:48
  • @prabeengiri, hi thanks a lot, there was a js error. New to this field. – Kent Dec 26 '13 at 11:05
2

Do like this:

function MY_MODULE_form_views_exposed_form_alter(&$form, &$form_state, $form_id) {
  if ($form['#id'] == 'FORM-ID') {
    $form['#attached']['js'] = array(
      drupal_get_path('module', 'MY_MODULE') . '/js/SCRIPT.js' => array(
        'type' => 'file',
        'group' => JS_LIBRARY, // or JS_DEFAULT, JS_THEME.. read this -  https://api.drupal.org/api/drupal/includes!common.inc/function/drupal_add_js/7
      ),
    );
  }
}

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.