How to load second DropDown list from Database after first DropDownList is changed

后端 未结 4 1526
遥遥无期
遥遥无期 2021-01-17 00:56

I am building a Web App. At some point a user needs to input data to a form. This form has several text fields and DropDownLists.

One of the DDLs is dep

相关标签:
4条回答
  • 2021-01-17 01:33

    Here's an example:

    http://tutorialzine.com/2011/11/chained-ajax-selects-jquery/

    Google is your friend :)

    0 讨论(0)
  • 2021-01-17 01:53

    Ajax is your best bet. this will help

    0 讨论(0)
  • 2021-01-17 01:55

    If the data in the second drop-down is dependent on the data in the first, then you will have to load the values of the second dropdown into a javascript object, like so:

    // Given the options in the first dropdown are: "foo", "bar", and "baz"
    var secondData = {
        foo: ['lorem', 'ipsum'],
        bar: [1,2,3],
        baz: []
    }
    

    Add a 'change' event to the first dropdown, and given the value of that dropdown, load the contents of the second dropdown with the values contained in the secondData object.

    0 讨论(0)
  • 2021-01-17 01:55

    If you're comfortable using jQuery (which I would highly recommend), something like this should do:

    $("#dropdown").on("change", function() {//change [dropdown] to the actual ID of your dropdown
        var selected=$(this).find("option:selected").val();//assuming your dropdown has a value to send, otherwise use text()
    
        $.get("options.php?selected="+selected, function(data) {
            var options=data.split("\n");
            var newSelectHTML="<select name=\"whatever\">\n";
    
            for (var i=0;i<options.length;i++) {
                newSelectHTML+="<option>"+options[i]+"</option>";
            }
    
            newSelectHTML+="</select>";
            $("#form").append(newSelectHTML);//again, change [form] to the correct ID.
        }
    }
    

    This code simply gets the value of the currently selected option of the DDL with the ID "dropdown" (change as necessary) and sends it to PHP file options.php in $_GET["selected"];. Assuming that file then outputs a list of options separated by a new line (\n). The JavaScript then takes that, splits it by line, loops through the options, and creates the HTML for a new DDL and appends that to element ID form. No error handling is there, but that, as they say, is an exercise for the reader. Whatever is returned is in the variable data.

    0 讨论(0)
提交回复
热议问题