I get a string like from server using jquery:
<option value='1'>1</option><option value='2'>2</option>
<option value='3'>3</option><option value='4'>4</option>
then I create a dropdown within a div:
$.get('server.php', function(data) {
$('#mydiv').html('<select id="mysel" name="mysel">'+data+'</select>');
});
problem is that when I create this, I want to select one option so:
$("#mysel").val("3");
but doesn't work! if I add an alert before calling this line, then this works!
alert('test');
$("#mysel").val("3");
can not find what is problem.
NOTE: I can not change the way I get data from server.
$("#mysel").val("3");is outside of the$.get() {}? The response from$.getis asynchronous so the$("#mysel").val("3");executes before the HTML<option>elements are added. Adding thealert()delays the execution long enough for the<option>to exist in that scenario. Solution: move$("#mysel").val("3");inside the$.get() {}body.