2

I'd like to get the following jQuery code to run on any forms on my site:

(function($) {
  // Hide any N/A radio buttons
  $('.form-radio[value=_none]').parent().hide();

  // Uncheck a radio button on double-click
  $('.form-radio').dblclick(function(){
    $(this).prop('checked', false);
  });
})(jQuery);

I've read that I can probably just add it to my template.php file, but I'd like to put it in a module. How would I do that?

UPDATE:

Thanks for the suggestions! So I went with option 3 because it seemed to make the most sense to me for my use-case. I still wasn't getting my jQuery to actually work though. I've updated it to this now:

(function($){      
  Drupal.behaviors.doubleClickNA = {
    attach: function (context) {
      // Hide the N/A radio button
      $('.form-radio[value=_none]').parent().hide();

      // Enable the double-click unchecker function
      $('.form-radio').dblclick(function(){
        $(this).prop('checked', false);
        $(this).parent().parent().$('.form-radio[value=_none]').prop('checked', true);
      });
    }
  };
})(jQuery);

That seems to get the N/A radio button to disappear, but the second function still doesn't work. The $('document').ready part was the key for the first function (duh, right?), but I believe I need to use a behavior to get the double click action to work after the page as finished rendering. What more am I missing here?

5

You have different ways/options to add custom javascript/jQuery file with your module.

Option 1: Add myscript.js in module info file (mymodule.info).

scripts[] = js/myscript.js

Option 2: Add myscript.js using hook_init and drupal_add_js

function mymodule_init() {
  drupal_add_js(drupal_get_path('module', 'MODULE_NAME') .'/js/myscript.js', 'file');
}

Option 3: Add myscript.js to any Drupal form or any callback that contains Drupal form

function mymodule_form_alter(&$form, &$form_state, $form_id) {
  $form['#attached']['js'][] = array(
    'data' => drupal_get_path('module', 'MODULE_NAME') . '/js/myscript.js', 
    'type' => 'file',
  );
}
0

The simplest way is to add it as a script file (eg. mysite.js) in the module directory and add:

scripts[] = mysite.js

to the .info file for the module. That way it will be aggregated with the other javascript files and will be an active library on all pages.

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.