Skip to content Skip to sidebar Skip to footer

Filter Dropdown Based On Other Dropdown Selection

I have 2 separate dropdown lists. I need to get each dropdown to filter each other. Every example I have seen so far is an example for dropdowns that have the options hard-coded in

Solution 1:

jquery can't run php on the page once it is loaded. You could use ajax, running the query to get the second set of options from another file.

<selectid="collector"><?php//code to generate initial collector options ?></select><selectid="date"><option>--Bill Date--</option></select>

In your jquery, target the first dropdown and then use load() to call a php file

$(document).ready(function(){   
    $("#collector").on('change', function(){
        filterItems(this.value);
    });     
});
functionfilterItems(value){    
    var destination = "#date";
    var url = "path/to/filterCode.php?v="+value;
    $(destination).load(url);
}); 

In the filterCode php file, get the value selected by the user

$selectedCollector = $_GET['v'];

Then use $selectedCollector to query your database and get the appropriate date options.

Then, inside your results loop:

echo'<option class="'.$date['Date'].'" value="'.$date['Date'].'">'.$date['Date'].'</option>';

The load() will take these echoed options and put them into #date.

Solution 2:

I think you need to populate #date drop-down based on #collector drop-down value, according to me best option is ajax.

here some basic example,

<selectid="collector"><optionvalue=""></option></select>

jut think this as your #collector drop-down there will be some options based on your data. Now you need to populate #date drop-down,

<selectid="collector"><optionvalue=""></option></select>

In page load you can load all the data if you want.

when #collector drop-down change you can send ajax request and retrieve data from database based on #collector value, like this

    $("#collector").on('change', function(){
       $.ajax({
         type: method,
         url: url,
         data: data,
         success: function(response) {
             //populate select box      
         } 
       }); 
   });

Below links will be helpful,

How to Use jQuery’s $.ajax() Function

Populate dropdown select with array using jQuery

Post a Comment for "Filter Dropdown Based On Other Dropdown Selection"