jQuery/Javascript: Autopopulate Dynamically Populated Elements
Problem
I am trying to auto-populate dynamically populated elements (eg
I've attempted implementing aselect
inputs). The problem is caused due to the asynchronicity of AJAX, so I need some sort of "wait until thread is complete".while
loop with a setTimeout(0), but that did not go as expected.
Demo
http://jsfiddle.net/vol7ron/wQZdM/
Conditions开发者_开发问答
- 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 ...
精彩评论