tags:

views:

28

answers:

1

I'm experiencing odd behavior after adding options to a select via ajax.

After adding the items to the select, I want to select one of the items in the list based on value.

I tried the following RIGHT after I called the function that adds the options to the select

fillSelect("someAjaxServerVar");
$("#theSelect").val("somevalue");

Oddly, the 2nd line is not run or isn't working. What is even more odd is that I placed the 2nd line as a separate click for a test button:

$("#testButton").click(function() {
     $("#theSelect").val("somevalue"); 
});

The above works, but I want to be able to change the value to a certain option as soon as the select is filled.

+2  A: 

It sounds like you might be making an asynchronous call. That is, it is running the second line BEFORE all the actions from the first line have completed. If this is the case, put all your following code into a callback.

nickf
That worked. Is there a way to deffer execution until after the previous function is complete (in this case the callback function of the Ajax)?
Baddie
put that code into the callback.
nickf
Besides that way?
Baddie
The only other (acceptable) way would be to put it into a `setTimeout` function, but that gives no benefit over a callback. You could use synchronous calls: it will solve the immediate problem, but it's a very bad idea overall.
nickf