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

后端 未结 4 1587
遥遥无期
遥遥无期 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: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="";
            $("#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.

提交回复
热议问题