0

I'd like to add my own JS functions to the Commerce "add to cart" form when a user makes selections on various product attributes.

When the user clicks through the options available, I need to scan the form using JS for the current values of the radiobuttons/selects. I need this to happen as soon as the form elements have changed.

edit: Having some success with the following, however since the form changes every single attribute this makes my javascript function run many, many times.

(function($) {
  Drupal.behaviors.watch = {
    attach: function(context, settings) {
      //look at form values here.
      //this fires after each form element is updated

    }
  }
})(jQuery);

Forgive me if this question sounds a bit lazy, I am reading the documentation, but I've not seen anything yet.

3
  • 1
    Are you using the 'context' parameter in your jQuery selectors to limit the scope of your jQuery commands? Please update your code example with some of the actual contents of your attach function.
    – Les Lim
    Commented May 8, 2015 at 18:43
  • repost as an answer, ha.. this was really the clue I needed. just checking the context to make sure it's even defined was enough.
    – user5482
    Commented May 8, 2015 at 19:51
  • Glad it was as easy as that!
    – Les Lim
    Commented May 8, 2015 at 22:53

1 Answer 1

0

When you use Drupal's "attach" behaviors, use the provided context parameter in your jQuery selectors to limit the selector scope to only the part of the page that is being modified by AJAX:

(function($) {
  Drupal.behaviors.watch = {
    attach: function(context, settings) {
      $('.my-input', context).val('foo');
    }
  }
})(jQuery);

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.