Javascript 根据另一个下拉列表中的选择填充下拉列表

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30316285/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 04:58:47  来源:igfitidea点击:

Populate dropdown list based on selection in another dropdown

javascriptphpjquerydrop-down-menu

提问by cyonder

First of all I would like to say that there are many questions like this one and this is a duplicated question but I tried to do it by myself by looking at other codes but I gave up after 1 hour.

首先,我想说有很多这样的问题,这是一个重复的问题,但我试图通过查看其他代码自己完成,但我在 1 小时后放弃了。

What I want to do is to populate dropdown list based on selection in another dropdown but both dropdown's options are coming from database.

我想要做的是根据另一个下拉列表中的选择填充下拉列表,但两个下拉列表的选项都来自数据库。

I don't know jQuery and I also saw that some people used onChange function to do what I needed to do.

我不知道 jQuery,我也看到有些人使用 onChange 函数来做我需要做的事情。

So, I would like to explain my problem. I have 2 dropdown. One of them is containing the school names and other one contains the course codes. What I need to do is, I want to show course codes based on the school you choose. Because every school has its own courses.

所以,我想解释一下我的问题。我有 2 个下拉列表。其中一个包含学校名称,另一个包含课程代码。我需要做的是,我想根据您选择的学校显示课程代码。因为每个学校都有自己的课程。

This is the first dropdown. foreach loop may look confusing. I simply echo options but if user selected school already, I echo user's school as selected. That's why I have if else statement there.

这是第一个下拉菜单。foreach 循环可能看起来很混乱。我只是回应选项,但如果用户已经选择了学校,我会回应用户选择的学校。这就是为什么我在那里有 if else 语句。

$query_schools = "SELECT * FROM SCHOOLS ORDER BY SCHOOL_TYPE ASC";
$query_users = "SELECT USER_SCHOOL FROM USERS WHERE USER_ID = $user1_id";

$schools_result = mysqli_query($dbConnection, $query_schools);
$users_result = mysqli_query($dbConnection, $query_users);

while($data = mysqli_fetch_assoc($users_result)){ $user_school = $data['USER_SCHOOL']; }

foreach($schools_result as $school_result){
    if($user_school == $school_result['SCHOOL_NAME']){
        echo "<option value='$school_result[SCHOOL_SHORT_NAME]' selected>$school_result[SCHOOL_NAME]</option>";
    }else{
        echo "<option value='$school_result[SCHOOL_SHORT_NAME]'>$school_result[SCHOOL_NAME]</option>";
    }
}

This is the second drop down and they are similar.

这是第二个下拉菜单,它们很相似。

$query_programs = "SELECT * FROM PROGRAMS ORDER BY PROGRAM_CODE ASC";
$query_users = "SELECT USER_PROGRAM FROM USERS WHERE USER_ID = $user1_id";

$programs_result = mysqli_query($dbConnection, $query_programs);
$users_result = mysqli_query($dbConnection, $query_users);

while($data = mysqli_fetch_assoc($users_result)){ $user_program = $data['USER_PROGRAM']; }

foreach($programs_result as $program_result){
    if($user_program == $program_result['PROGRAM_CODE']){
        echo "<option value='$program_result[PROGRAM_CODE]' title='$program_result[PROGRAM_NAME]' selected>$program_result[PROGRAM_CODE]</option>";
    }else{
        echo "<option value='$program_result[PROGRAM_CODE]'>$program_result[PROGRAM_CODE]</option>";
    }
}

if it was pure php, I chould do like this for the first query:

如果它是纯 php,我可以在第一个查询中这样做:

$query_programs = "SELECT * FROM PROGRAMS WHERE PROGRAM_SCHOOL = '$user_school' ORDER BY PROGRAM_CODE ASC";

Thank you for your help.

感谢您的帮助。

回答by Guruprasad Rao

I am not pretty much sure about phpserver side coding but I can tell you how you can achieve load data from ajax.

我不太确定php服务器端编码,但我可以告诉你如何从ajax.

Say you have below 2 select

假设你有以下 2 select

<select class='school'>
     <option value="sc1">school1</option>//Place your school codes in value for option
     <option value="sc2">school2</option>
     <option value="sc3">school3</option>
</select>

<select class="course">
</select>

Now on change of first dropdown .schoolperform an ajax call as below:

现在更改第一个下拉列表,.school执行如下 ajax 调用:

$('.school').on('change',function()
{
      var selectedSchool=$(this).find('option:selected').val(); //Select the school code which is stored as value for option
      $.ajax({
             url:'/SomeFunction/', //Write a function in the server side which accepts school code as argument
             type:'POST',
             dataType:'json',//return type from server side function [return it as JSON object]
             contentType: "application/json",
             data: JSON.stringify(selectedSchool), //Pass the data to the function on server side
             success: function (data) { //Array of data returned from server side function
                    $.each(data,function(value){
                          $('.course').append('<option>'+value+'</option>');
                    });
             },
             error:
                function (data) {
                    //display any unhandled error
             }
       });
});

回答by Jobst

On Stackoverflow there is an example that has a jsfiddle attached: Populate one dropdown list based on the selection of other dropdown list

在 Stackoverflow 上有一个附有 jsfiddle 的例子: Populate one dropdown list based on the selection of other dropdown list

It works by creating one already populated select and one EMPTY one:

它的工作原理是创建一个已填充的选择和一个空的:

<select id="cat">
    <option val="car">car</option>
    <option val="phone">phone</option>
</select>
<select id="item">
</select>

The first select (Id=cat) has a function attached, which basically is jquery's way of "onChange":

第一个select(Id=cat)附加了一个函数,基本上就是jquery的“onChange”方式:

(function() {
      $('#cat').change(function(){
        populateSelect();
    });
});

so whenever you CHANGE (i.e. select another item of the "id=cat" selection box it calls the next function which then populates the other select box "id=item" with new "<option .... option>" values:

所以每当你改变(即选择“id=cat”选择框的另一个项目时,它会调用下一个函数,然后用新的“<option .... option>”值填充另一个选择框“id=item”:

cars=new Array("Mercedes","Volvo","BMW","porche");
phones=new Array('Samsung','Nokia','Iphone');

function populateSelect(){
    // get the value that was selected so we can populate the other one
    cat=$('#cat').val();
    // clear the other select box
    $('#item').html('');
    // now fill with new code depending on the slection
    if(cat=='car'){
        // this is jquery's way of a for loop
        cars.forEach(function(t) { 
            // $('#item') refers to the EMPTY select list
            // the .append means add to the object refered to above
            $('#item').append('<option>'+t+'</option>');
        });
    }
    elsif(cat=='phone'){
        phones.forEach(function(t) {
            $('#item').append('<option>'+t+'</option>');
        });
    }
}

回答by omikes

When you are echoing-in the OPTION statements give each type of course code a unique value, and in the second select box give each option a matching class.

当您在 OPTION 语句中回显时,为每种类型的课程代码指定一个唯一值,并在第二个选择框中为每个选项指定一个匹配的类。

Select box 1 would have:

选择框 1 将具有:

echo "<SELECT onchange='changeCourseCodes(this)'>"
echo "<OPTION value='UNIQUE1' name='Course Type 1'>"
//... more options, then close select

Then be sure to give an ID to the second select box, the one which displays the changing values:

然后确保为第二个选择框提供一个 ID,该框显示变化的值:

echo "<SELECT id='courseCodes'>"
echo "<OPTION class='UNIQUE1'>"
// options, end select, etc.

As for the jQuery, you could show just one of the OPTION types, hiding the rest with css and use this command to hide/show the other list when the option is changed.

至于 jQuery,您可以只显示 OPTION 类型之一,用 css 隐藏其余类型,并在选项更改时使用此命令隐藏/显示另一个列表。

<script>
  function changeCourseCodes(selectedOption)
  {
     var classType = $(selectedOption).val(); // get the selected class type
     $('#courseCodes > OPTION').hide(); // hide all options
     $('.' + classType).show(); // show just the chosen ones
  }
</script>

This is UNTESTED code though, a stab in the dark. Something along these lines will get it done.

这是未经测试的代码,在黑暗中刺伤。沿着这些路线的事情将完成它。

回答by Harshad Ranganathan

I have implemented the same using javascript. In my case the input is json. You can just pass the input to the onchange function call or use ajax within the function.

我已经使用 javascript 实现了相同的功能。在我的情况下,输入是 json。您可以将输入传递给 onchange 函数调用或在函数内使用 ajax。

HTML

HTML

<table>
<tr>
    <td>
        <select onchange="f(event)">
            <option value="" disabled selected style="display:none;">--Select--</option>
            <option>Offshore</option>
            <option>Onsite</option>
        </select>
    </td>
    <td>
        <select>
            <option>------</option>
        </select>
    </td>
</tr>
   <tr>
    <td>
        <select onchange="f(event)">
            <option value="" disabled selected style="display:none;">--Select--</option>
            <option>Offshore</option>
            <option>Onsite</option>
        </select>
    </td>
    <td>
        <select>
            <option>------</option>
        </select>
    </td>
</tr>

Javascript

Javascript

 window.f=function(event){
 onoffelem=event.target;
 locelem=event.target.parentNode.nextSibling.nextSibling.children[0];
 locelem.options.length=0;
 offmap=JSON.parse('{"11":"Chennai","12":"Kolkatta"}');
 onsitemap=JSON.parse('{"1":"USA","2":"Canada"}');
 selectedVal=onoffelem.options[onoffelem.selectedIndex].text;
    if(selectedVal=="Offshore"){
         for(var key in offmap){
             option = document.createElement( 'option' );
             option.value = key;
             option.text = offmap[key]
             locelem.add(option);   
         }
    }else{
        for(var key in onsitemap){
             option = document.createElement( 'option' );
             option.value = key;
             option.text = onsitemap[key]
             locelem.add(option);   
         }
    }

}

JSFiddle Demo

JSFiddle 演示