简体   繁体   中英

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

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);

        });

    });
});

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

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

Have fun :-)

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);

    });

});

});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM