Mike Mike - 2 months ago 7
Javascript Question

Dependent dropdown lists - autoload

I have two dependent dropdown lists: products and releases. When I change the product, the list of releases of this product reloads so that it lists releases only for the chosen product. I used 'change' method to load releases when the product is changed but when the page loads there were no releases listed for the default product. I couldn't select a release if there was only one product. To solve this I added an additional 'focus' method to overcome this but i still don't know how to make the releases load when the page loads.

<script type="text/javascript">
$(document).ready(function() {
$("#product").focus(function() {
$.get('../deliveries/loadReleases.php?productName=' + $(this).val(), function(data) {
$("#release").html(data);
});
});

$("#product").change(function() {
$.get('../deliveries/loadReleases.php?productName=' + $(this).val(), function(data) {
$("#release").html(data);
});
});

});

</script>

Answer

No need of focus. You can try this:

$(document).ready(function() {

    $("#product").change(function() {
        $.get('../deliveries/loadReleases.php?productName=' + $(this).val(), function(data) {
            $("#release").html(data);
        }); 
    }).trigger("change");

});

It will trigger the change event immediately after attaching the handler.