根据另一个下拉菜单填充下拉菜单最好最简单的方法是什么? [英] What's the best and easiest way to Populate a dropdown based on another dropdown

查看:111
本文介绍了根据另一个下拉菜单填充下拉菜单最好最简单的方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

很简单,我有一个动态填充数据的下拉菜单:

Very simply, I have one dropdown menu dynamically populated with data:

SQL代码

$querycourse = "SELECT course, COUNT(course) AS count FROM acme WHERE course IS NOT NULL GROUP BY course ";
$procc = mysqli_prepare($link, $querycourse);
$queryc =  mysqli_query($link, $querycourse) or die(mysqli_error($link));

PHP代码

echo "<select name='course[]' value='' multiple='multiple' size=10>";
            // printing the list box select command
            echo "<option value=''>All</option>";
            while($ntc=mysqli_fetch_array($queryc)){//Array or records stored in $nt
            echo "<option value=\"$ntc[course]\">\"$ntc[course]\"</option>";
            /* Option values are added by looping through the array */
            }
            echo "</select>";// Closing of list box 

我需要的是根据第一个下拉框中的选择填充数据的另一个下拉列表。

What I need is another dropdown that is populated with data based on a selection from the first dropdown box.

我正在使用MySQL,PHP,Javascript,也可以(推送)使用jQuery。我没有Ajax的经验。

I am using MySQL, PHP, Javascript and can also (at a push) use jQuery. I have no experience in Ajax.

有没有人能够指出我正确的方向?

Would anyone be kind enough to point me in the right direction?!

提前感谢,一如既往,

荷马。

推荐答案

第一和最佳方法(如果您具有或可能具有足够的选项特定数据)

使用AJAX。这是最简单的方法,我认为,与其他实现方式相比较。使用Jquery来实现AJAX。它使AJAX成为一块蛋糕!在这里,我分享了我的蛋糕 -

First and Best Method (If you have or may have enough option specific data)
Use AJAX. It is the easiest way, I think, compared to the other ways to implement the same. Use Jquery to implement AJAX. It makes AJAX a piece of cake! Here I share my piece of cake for you -

以下是您需要的完整代码 -

Following is roughly the complete code you need -


  • 在您首次选择时调用javascript函数populateSecondDropdown() -

  • Call a javascript function populateSecondDropdown() on your first select like this -



    echo "<select  name='course[]' value='' multiple='multiple' size=10 onchange='populateSecondDropdown(this, 'http://yourprojectUrl','Any Subject');'>";
            // printing the list box select command
            echo "<option value=''>All</option>";
            while($ntc=mysqli_fetch_array($queryc))
            {//Array or records stored in $nt
                echo "<option value=\"$ntc[course]\">\"$ntc[course]\"</option>";
                /* Option values are added by looping through the array */
            }
            echo "</select>";// Closing of list box 


  • 在populateSecondDropdown()函数内定义一个ajax调用 -

  • Define an ajax call inside inside the populateSecondDropdown() function -

    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js"></script>
    
    <script  type="text/javascript">  
        function populateSecondDropdown(object,baseUrl)
        {
            $.ajax({
            type: "POST", 
            url: baseUrl+"/ajax/fetchOptions.php", 
            data: { id_option: $(object).val(), operation: 'get_subjects' },
            dataType: "json",
            success: function(data) 
            {
                //Clear options corresponding to earlier option of first dropdown
               $('select#secondDropdown').empty(); 
               $('select#secondDropdown').append('<option value="0">Select Option</option>');
                       //Populate options of the second dropdown
               $.each( data.subjects, function() 
               {    
                   $('select#secondDropdown').append('<option value="'+$(this).attr('option_id')+'">'+$(this).attr('option_name')+'</option>');
               });
               $('select#secondDropdown').focus();
            },
                beforeSend: function() 
                {
                    $('select#secondDropdown').empty();
                    $('select#secondDropdown').append('<option value="0">Loading...</option>');
                },
                error: function() 
               {
                  $('select#secondDropdown').attr('disabled', true);
                  $('select#secondDropdown').empty();
                   $('select#secondDropdown').append('<option value="0">No Options</option>');
              }
            });
         }
    </script>
    




    • 最后,查询获取第二个下拉列表中的选项AJAX处理器文件fetchOptions.php。你可以使用$ _POST ['id_option']来获取它下面的选项。这里的数据库查询应该为每个选项提取 option_id option_name 字段(如jQuery代码里面的 $。each )并返回一个json编码数组,如下所示: -

      • And finally the query to fetch 2nd dropdown's options in the AJAX processor file fetchOptions.php. You can use $_POST['id_option'] here to fetch the options under it. The database query here should fetch the option_id and option_name fields for every option (as expected by the jquery code inside $.each) and return a json encoded array like this:-

        return json_encode(array("subjects" => $resultOfQuery));
        


      • 第二种方法(仅使用javascript)


        • 获取第二个下拉列表中的所有数据按第一个下拉列表的字段分组。例如。让我们在第一个下拉列表中显示课程,并在第二个

        • Fetch all the data for the second dropdown grouped by the field of the first dropdown. E.g. let's take courses displayed in the first dropdown and subjects under courses displayed in the 2nd


        • 中显示课程的课程创建第二个下拉列表的所有选项。在创建类似于以下选项的课程中分配课程: -

        • Create all the options of the 2nd dropdown. Assign classes equal to the courses while creating the options like this:-

        $querycourse = "SELECT course, subject FROM subjects WHERE subject IS NOT NULL GROUP BY course ";
        $procc = mysqli_prepare($link, $querycourse);
        $queryc =  mysqli_query($link, $querycourse) or die(mysqli_error($link));
        
        echo "<select  name='subjects[]' value='' multiple='multiple' size=100>";
        echo "<option value=''>All</option>";
                    while($ntc=mysqli_fetch_array($queryc))
                    {//Array or records stored in $nt
                        echo "<option value=\"$ntc[subject]\" class=\"$ntc[course]\">\"$ntc[subject]\"</option>";
                    }
                    echo "</select>";
        


      • 然后定义 onchange =displaySubjectsUnderThisCourse(this); / code>为第一个下拉列表并写这个javascript: -

      • Then define onchange="displaySubjectsUnderThisCourse(this);" for the first dropdown and write this javascript :-

         function displaySubjectsUnderThisCourse(object)
         {
             var selectedCourse = $(object).val();
            //Display the options with class = the selected option from first dropdown
            $("."+selectedCourse).removeClass("hidden"); //define a class hidden with display:none;
        
           $('option:not(.selectedCourse)').hide();  // hide all options whose class is other than selectedCourse - Not sure whether this will work or not, though
        
          //Deselect any previous selections
          //If single option selection is allowed
          $('select#secondDropdown option').attr('selected', false); 
          // or following if multiple selection is allowed (needed for IE)
          $('select#secondDropdown option').attr('selectedIndex', -1); 
        
        
        }
        

        这里的基本想法是隐藏/显示选项组,但我的代码可能有错误。

        The basic idea here is to hide/display option groups but my code may have errors.

        请注意,第二种方法(获取所有选项值)只有在数据量少的情况下才会更好,并且确保将来会始终存在较少的数据。但是,由于没有人能够对未来有所了解,建议始终使用AJAX方法。

        Finally, please note, the second method (fetching all the option values) would be better only if you have limited small amount of data and are very sure there will always be less data in future. But, since nobody can be so certain about the future, it is advisable to use the AJAX method always.

        这篇关于根据另一个下拉菜单填充下拉菜单最好最简单的方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

  • 查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆