heron
heron

Reputation: 3661

Set exact option for select-box which generated on the fly with AJAX

My AJAX function generates #parent select-box on the fly. The problem is, i can't set exact option after menu generation

Tried

window.onload = function () {
var parent='1';
$('#parent').val(parent);   
}   

And

$(document).ready(function () {
var parent='1';
$('#parent').val(parent);   
});

no success!. Any suggetions?

Upvotes: 3

Views: 190

Answers (2)

enloz
enloz

Reputation: 5834

Basiclly... You need to be sure that in <option> there is a value. Here is example

(HTML - script.html)

<select id="parent">
    <option value="0">First</option>
    <option value="1">Second</option>
</select>

(JS - index.html)

$(function(){
    $.get('script.html', function(data){
        $('#someDiv').append(data); // appends your select list to some div

        /* after <select> is appended */
        var parent = '1';
        $('#parent').val(parent); // selects "Second" option
    })
})

Upvotes: 0

Quentin
Quentin

Reputation: 943995

Neither onload nor ready will wait for an Ajax request. Move the function to the callback that you pass to the success handler.

Upvotes: 1

Related Questions