javascript/php won't load data for first option in dependent dropdown

74 views Asked by At

I'm having a problem with a script that is part borrowed and part my own, it is javascript and php that populates two dropdown lists, with options in the second being dependent on what the user selects in the first. For some reason, it won't load the options in the second dropdown when the initial option is selected in the first, either on page load or if it is selected manually (if the options were 'a, b, c, d, e...etc', it won't load anything for 'a').

I think it might be something to do with the javascript document ready function, but I'm afraid I know very little about javascript. This is the javascript code:

        $(document).ready(function () {
    $.getJSON("getOutcome.php", success = function(data)
    {
        var options = "";

        for(var i = 0; i < data.length; i++)
        {
            options += "<option value ='" + data[i].toLowerCase() + "'>" + data[i] + "</option>";
        }

        $("#slctOutcome").append(options);

        $("#slctProxy").change();
    });

    $("#slctOutcome").change(function()
    {   
        $.getJSON("getProxies.php?outcome=" + $(this).val(), success = function(data)
    {
            var options = "";

            for(var i = 0; i < data.length; i++)
            {
                options += "<option value ='" + data[i].toLowerCase() + "'>" + data[i] + "</option>";
            }

            $("#slctProxy").html("");
            $("#slctProxy").append(options);

        });

    });
});
2

There are 2 answers

0
Mr Magnum On

Change event is only fired, when selection is changed - not when filled ;-)

Try adding $("#slctOutcome").trigger("change"); at pre-last line

Have fun :-)

0
G Wonsley On

Try the below. Second function wasn't being called in first function.

 $(document).ready(function () {
$.getJSON("getOutcome.php", success = function(data)
{
    var options = "";

    for(var i = 0; i < data.length; i++)
    {
        options += "<option value ='" + data[i].toLowerCase() + "'>" + data[i] + "</option>";
    }

    $("#slctOutcome").append(options);

    $("#slctOutcome").change();  //<-Here
});

$("#slctOutcome").change(function()
{   
    $.getJSON("getProxies.php?outcome=" + $(this).val(), success = function(data)
{
        var options = "";

        for(var i = 0; i < data.length; i++)
        {
            options += "<option value ='" + data[i].toLowerCase() + "'>" + data[i] + "</option>";
        }

        $("#slctProxy").html("");
        $("#slctProxy").append(options);

    });

});

});