Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
239 views
in Technique[技术] by (71.8m points)

php - What's the best and easiest way to Populate a dropdown based on another dropdown

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

SQL Code

$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 Code

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.

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?!

Thanks in advance, as always,

Homer.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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 -

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

Second Method (Using only 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>";
      
    • 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.

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...