开发者

jQuery/Javascript: Autopopulate Dynamically Populated Elements

Problem


I am trying to auto-populate dynamically populated elements (eg select inputs). The problem is caused due to the asynchronicity of AJAX, so I need some sort of "wait until thread is complete".

I've attempted implementing a while loop with a setTimeout(0), but that did not go as expected.

Demo


http://jsfiddle.net/vol7ron/wQZdM/

Conditions开发者_开发问答


  1. I cannot edit the source code, since this is supposed to be a tool to auto-populate forms for testing.


You should use MutationObserver to handle this. Observe all the select elements for future changes.

Here's the updated fiddle.

Basically here's how I changed it:

var observer  = new MutationObserver(function (mutations) {
    mutations.forEach(function (mutation) {
        handleSelect(mutation.target);
    });
});
$('select').each(function () {
    observer.observe(this, { childList : true }); // We observe the elementw
    handleSelect(this);
});

function handleSelect(el) {
    var t = $(el);
    var c = t.children('option');

    t.val(c.eq(1).val()); // set value to second option value
    t.trigger('change'); // calls the onChange even if it doesnt exist
}

Note that MutationObserver is available only in modern browsers. You can use either of the follwoing shims/pollyfills(they each have different browser support, so choose the one you need):

  • https://github.com/megawac/MutationObserver.js
  • https://github.com/Polymer/MutationObservers

But this might be kind of sneaky in testing tools. Generally with my experience from selenium or casperjs, I just would wait for the new options to arrive then select that option.


jQuery ajax function takes a success callback function. You can use that to auto populate after the ajax call has successfully completed. Are you saying your cannot modify the ajax code?


Add it to your

success : function(){}

callback function. But if you really can't edit your code, you can't fix it ...

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜