1

I am trying to get jQuery to send a mousedown event to the Drupal 7 "add another item" button for a multi-value field, then wait until the ajax call has completed before filling in that new blank row with data from an element in a jQuery object (that has several elements). I need to use a loop to cycle through the elements (ingredients) in this jQuery object, but no matter what I try my page dies...

Currently, I have something like the following:

i = 0;
ingredients = newHtml.find('.recipe_ingredients > li');
ingredientsLength = ingredients.length;

$('#edit-field-ingredients-und-add-more').mousedown();

while(i < ingredientsLength) {
    if ( document.readyState !== 'complete' ) {
        // code to fill in the new blank row with data from 'ingredients'
        $('#edit-field-ingredients-und-add-more').mousedown();
        i++;
    }        
}

Because I don't yet know how to issue the ajax call myself using jQuery (or using Drupal) I've been trying to just check whether the call has completed by using .readyState and other hack-like methods. I'm just not sure what to try next!

Am I going about this the completely wrong way? Is there a straightforward way to make the "add another item" multi-value field ajax call using jQuery? Any help would be greatly appreciated...

1 Answer 1

1

I am not sure if there's a nicer way in Drupal 7, but in Drupal 6 you could use jQuery(document).ajaxComplete with the settings.url property to tell when a specific "Add another item" click had finished.

Start with:

(function($) {
    $(document).ajaxComplete(function(e, xhr, settings)
    {
        alert(settings.url);
    });
}(jQuery));

Once you've identified the right settings.url for your field, change that to:

(function($) {
    $(document).ajaxComplete(function(e, xhr, settings)
    {
        if (settings.url == "the path from step 1") {
            // Code to populate your fields here
        }
    });
}(jQuery));

And voila!

You might want to read the page by Jay Matwichuk where I originally learned this technique awhile back. All credit to him (and nclavaud for his comment there), really.

Sign up to request clarification or add additional context in comments.

1 Comment

Wow, I've been searching all over for something like that! Thank you... it works!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.