Background info:
I have a function that when called creates select list inside a form and populates it. After that the script runs through the options in the list and looks for a certain value. If the value is there, the script 'selects' that option.
Problem:
Because the list is dynamically created and is some times very large, it takes a while to load. When this happens, the second part of the script (the part that selects an option), does not do anything because the select list has not had time to load.
Idea for a solution:
What would be nice is to call the second part of the function (as a separate function) in an onload event for the select list. But select lists are not supposed to have an onload attribute. The other idea is to simply add a delay, but one day the delay may not be long enough.
Thanks in advance for any help
views:
909answers:
4Using a delay is not reliable. Whatever you're using to populate the select list should call the function directly when it is finished.
alternately:
Since there is no "onload" event for the select all you can really do it have a function that calls itself after a timeout. If the length of the items in the select list has changed from zero, you know something is currently adding items (the start-point). If the start-point has been reached and nothing has changed after the next timeout, you can assume items have stopped being added to the list, so you can then run the second function.
Why don't you make the function which selects option a callback function. It will be call at the end of the function which creates the list. E.g.
function createList(onComplete) {
// Create the list and maybe other tasks
onComplete();
}
Note: might not be like this but I think you've got the idea...
How are you doing your AJAX call? Most AJAX libraries will provide the mechanism to do a callback on successful completion. For example in jQuery:
$("#myList").load("ajax.url", function(){
//your content has been loaded, so you can do your selection logic here
});
If you're handling the ajax response manually & building your list in javascript, then you're already have code that knows when the list is finished, so you can just do the selection part once that has finished rather than as a separate function (like as zyeming has suggested).
If that doesn't help you, it might be worth posting some code so people can give you a more specific answer.
Ok, I have finally fixed the issue. The solution was completely different than what was discussed here. Basically, I was using 'new Option(value, text)' to add options to my list. I ended up throwing in a if statement and when a value equal what I needed is used new Option(value, text, true). and that solved the problem. All in a day's work.