0

I have set an ajax callback to a form using the form api #ajax. I also have custom jquery in a file which styles part of the page and sets click handlers. I found something funny - my custom javascript only begins working AFTER the ajax has been called on the drupal form. Before I that form api ajax is called, it doesn't work.

Why would this be?

EDIT:

I am attaching my behaviors like this:

(function($) {
  Drupal.behaviors.updateCart =  {
    'attach': function(context) {
    $(document).ready(function () {...

This file is being included inside of my modules hook form alter:

if($form_id == 'commerce_checkout_form_checkout') {
  drupal_add_js('sites/all/modules/my_subscription/js/updateCart.js');
}
  • really depends on how you are including the custom jquery in a file and if it is wrapped in the appropriate Drupal behavior handlers, etc. – Jimajamma Nov 15 '13 at 16:39
  • I have added the attach code. – user1015214 Nov 15 '13 at 17:22
  • I don't think this is what's causing the issue, but Drupal behaviors are called when the DOM is loaded. That means you don't need that extraneous $(document).ready(function() ... call from within the attached behavior function. – Evil E Nov 15 '13 at 18:33
  • @EvilE - Hey, that did it! Commenting out that line made it work! If someone could explain to me what was happening, that would be great! – user1015214 Nov 15 '13 at 19:06
  • Great, I'm glad it's resolved! I'll copy that comment into an answer so 1) it can help other people who get here, and 2) you can accept it! – Evil E Nov 15 '13 at 19:56
1

Even with the extraneous jQuery ready function within the behavior, it should still work. I guess it depends on what code resides within the javascript function and if all the jQuery selectors actually exist at that point. I would change two things to make it more "drupal"

  1. Per my earlier comment, remove the jQuery ready function from within the attached behavior function
  2. Attach the form javascript using the Form APIs #attached property. See here for more info.
0

The reason the extra ready function fails is because you're defining a callback to the event (page ready), in the processing of a callback to that same event... eg. the callback definition is added, to an already fired event.

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.