4

I am trying to add some js functionality to an unlimited value field in Drupal 7, it works on page load, but disappears after adding or removing an item, and I did not find a way to notify my code that the table is reloaded, and it is time to reinitialize those functions on the fields. How can I do this?

10
  • I don't know how your code is, but did you try the live() (api.jquery.com/live) method ?
    – Countzero
    Feb 29, 2012 at 17:44
  • I use this to add event listeners to the inputs, and it works, but I can't find a way to use it to run code immediately after loading, and I want to do that too.
    – Nord
    Feb 29, 2012 at 18:36
  • You could check the ajaxComplete (api.jquery.com/ajaxcomplete) event, but be aware it's not element dependant but triggered on a global basis.
    – Countzero
    Feb 29, 2012 at 18:45
  • Might work as last resort, but it would interfere with other ajax calls (like, an autocomplete field on the same form). Seeing how customizable other parts of Drupal are, it is hard to believe there is no 'official' way to do this.
    – Nord
    Feb 29, 2012 at 19:10
  • If there is one, I don't know about it. Did you search d.o for this ? The last time I investigated, there was work going on for D8 about lazy loading and that kind if stuff, but I can't tell you more.
    – Countzero
    Mar 1, 2012 at 7:12

1 Answer 1

4

Create a Drupal behavior. It will be attached to each field when the page loads as well as to new fields added after any ajax calls (adding or removing).

Here is a basic example that will log a click on the text boxes in the field field_fieldname

(function ($) {
  // Logclick is an arbitrary unique behavior name
  Drupal.behaviors.logclick = {
    // Context here allows your function to run on ajax calls
    attach: function(context, settings) {
      // Your custom jQuery goes here
      $(".field-name-field-fieldname input.form-text",context).once('logclick',function() {
        $(this).click(function() {
          console.log('text box clicked');
          return false;
        });
      });
    }
  };
})(jQuery);

logclick can be changed to whatever you want to call your behavior.

2
  • I can not try this now (without rebuilding a similar environment again, and I do not want that now), but it seems to do what I needed, thanks! It might be useful next time.
    – Nord
    Apr 20, 2012 at 4:00
  • I met a similar problem in D6, and this solution worked. Thanks again!
    – Nord
    Apr 29, 2012 at 0:54

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.