I have a SELECT
element in a form which I'm populating using AJAX when the select option changes. This works really well using the following code:
$(function() {
function populate() {
$.getJSON('/action/' + $(this).val(), {}, function(data, textStatus) {
var el = $('select#two');
el.html(''); // empty the select
$.each(data, function(idx, jsonData) {
el.append($('<option></option>').val(jsonData.id).html(jsonData.name));
});
});
}
$("select#one").change(populate);
});
Of course this only works when the first drop down is first changed. What I'd like to do is use the same method to pre-populate the second drop down when the page firsts loads.
The only way I can think of is to modify the getJSON
call as follows:
$.getJSON('/action/' + $("select#one").val(), {}, function(data, textStatus)
(i.e. don't use $(this)
)
and then simply calling this at the bottom of the 'on load' initialiser block:
populate();
Whilst this works, it just doesn't feel right. Can anyone suggest a better solution?