Back to Fred Mac Donald's Blog
I had a situation where I potentially could have a long list of dynamically added options to choose from a dropdown list. These options could/or could not be known to the user that need to make the selection. So the solution was to come up with a method to easily filter the populated list to “find” the option that would best match the users expectations
The form consists of two elements.
A normal text input field
<!-- The search box →
<input name="sku" type="search" class="type_data search" id="searchbox" placeholder="filter dropdown list..">
A dropdown list
The dropdown list is populated from a mysql query initially. This allow the previously saved option to be displayed as well as the full list of options.
<!-- The Dropdown List --> <select class="type_data" name="sto_id" id="sto_id"> <option value="">Select one...</option> <?php do { ?> <option value="<?php echo $row_Recordset1['id_prd']?>"<?php if (!(strcmp($row_Recordset1['id_prd'], $row_rsshop_pos_stock_list['sto_id']))) {echo "SELECTED";} ?>><?php echo $row_Recordset1['name_prd']?></option> <?php } while ($row_Recordset1 = mysql_fetch_assoc($Recordset1)); $rows = mysql_num_rows($Recordset1); if($rows > 0) { mysql_data_seek($Recordset1, 0); $row_Recordset1 = mysql_fetch_assoc($Recordset1); } ?> </select>
The jquery check for the “key-up” events. This will trigger the search function every time the user types a character. The functions calls a php file that will access the database and retrieve relevant information and return this to the dropdown list
<script type="text/javascript"> jQuery(document).ready(function($){ $(".search").keyup(function() { var searchbox = $(this).val(); var dataString = 'searchword='+ searchbox; if(searchbox=='') {} else { $.ajax({ type: "POST", url: "jquery/ajax_stock_search.php", data: dataString, cache: false, success: function(html) { $("#sto_id").html(html).show().listview('refresh'); } }); }return false; }); }); </script>
<?php require_once('siteConn.php'); ?> <?php mysql_select_db($database_siteConn, $siteConn); if($_POST) { $q=$_POST['searchword']; $sql_res= "SELECT products_prd.sku_prd, products_prd.name_prd, products_prd.id_prd FROM products_prd WHERE products_prd.sku_prd LIKE '%$q%' OR products_prd.name_prd LIKE '%$q%' LIMIT 10"; $result = mysql_query($sql_res, $siteConn) or die(mysql_error()); $hasresult = false; //Set flag for no results while($row=mysql_fetch_array($result)) { $fname= $row['sku_prd'].' - '.$row['name_prd']; ?> <option value="<?php echo $row['id_prd'];?>"><?php echo $fname;?></option> <?php $hasresult = true; // Set flag if results found } if(!$hasresult) // if no results display this { ?> <option value="">No records found...</option> <?php } } ?>