How to auto-fill 2 drop-down and text-box based upon on the first drop-down value selected?

I’d say it’s a relatively easy thing to do using Ajax and Jquery, as long as you can rely on your users having javascript enabled on their browsers. Consider this short html page that displays the initial drop-down list:

<script src="../jquery-1.11.1.js"></script>
<select name="mainlist" id="main-list" >
<option value="1">Select Category</option>
<option value="2">Category 2</option>
<option value="3">Category 3</option>
<option value="4">Category 4</option>
</br></br></br><div id="subcats">
<select name="subcat" id="subcat-list">
<option value='1'>Select Number</option>

$('#main-list').on('change', function(){
  var mainselection = this.value; // get the selection value
    type: "POST",  // method of sending data
    url: "subcategory.php", // name of PHP script
    data:'selection='+mainselection, // parameter name and value
    success: function(result){ // deal with the results
      $("#subcat-list").html(result); // insert in div above

This draws a drop-down list with an id of main-list. The JavaScript function monitors for the selected value in that list being changed, and when it does change, it grabs the current selection into a variable called mainselection, which it then passes to your PHP code as a parameter called selection. Your PHP code is then something like this:

$sel = $_POST['selection'];
// validate it
// connect to the database
// run a query to retrieve the other information 
$query = "select * from subcats where maincat = " . $sel;
// echo the information out to the screen
// while $row = $result->fetch() { 
// echo "<option>" . $row['subcatname'] . "</option>"
// }

I have left that as mainly pseudo-code so you can fill in the blanks, and I’ve missed out various bits such as actually executing the query - it’s intended as a pointer, not working code. When the data is echoed from your PHP routine, it comes back to the calling JavaScript in the result variable, which is then inserted into the main page html in the second drop-down list in the “success” section.

One thing I haven’t dealt with (because my example code doesn’t do it) is how to return more than one value. In the example, I’m just building up the html that goes into a second drop-down, and the calling JavaScript grabs that output as a variable. You’ll need to return it in two separate variables to be able to split it and send part to the drop-down and part to the text box. It’s probably going to need you to use something like JSON-encoding, but I’d recommend you get it working with a single value first, then expand on it.

You could do it with PHP alone, but it would be a bit more “clunky”. When the user makes a selection in the first drop-down, they’d have to submit the page, whereupon the PHP would extract the next level of data and re-draw the screen, filling in the second drop-down and the text box. I’m sure you’ve seen sites that work that way.

1 Like