Make a Dropdown with Search Box using jQuery

You already know that in HTML there is no search option in the dropdown element. When you press any single key on the dropdown then it takes you to the option but not allows you to search whole or particular string.

There are many jQuery plugins which do this for you.

But in this tutorial, I am not using any jQuery plugins for implementing it.

When it’s required?

This kind of feature generally requires when we have the long list of options in the Select element and want to make an easier navigation for users.

By this way, you enable user to search option on dropdown

The most common example is Country Dropdown which you have seen on many websites when you go for Registration.

What in the Demonstration ?

Creating a simple form which also contains a drop-down element. When the dropdown gets clicked then showing the Search Box and according to the input show suggestion.

Make a Dropdown with Search Box using jQuery


Contents

  1. HTML
  2. CSS
  3. PHP
  4. jQuery
  5. Demo
  6. Conclusion

1. HTML

In HTML, create a two input elements and a Dropdown. Also adding an another Textbox for displaying search field on Dropdown Click.

Completed Code

<div class='container'>
 <div id="div_reg">
  <h1>Register</h1>
  <div>
   <input type="text" class="textbox" id="txt_uname" name="txt_uname" placeholder="Username" />
  </div>
  <div>
   <input type="password" class="textbox" id="txt_uname" name="txt_pwd" placeholder="Password"/>
  </div>
  <div class="content_sel">
   <select id='sel_search'>
    <option value='0'>Select Department</option>
   <?php 
    $query = "select * from department order by depart_name";
    $result = mysql_query($query);
    while($row = mysql_fetch_array($result) ){
     echo '<option value="'.$row['depart_name'].'">'.$row['depart_name'].'</option>';
    }
   ?>
   </select> 
   <input type='text' id='txt_search' >
  </div> 
  <div>
   <input type="submit" value="Submit" name="but_submit" id="but_submit" />
  </div>
 </div>
</div>

2. CSS

Applying some CSS to Search Layout.

Completed code

#sel_search{
 width: 99%;
 padding: 3px;
 position: relative;
}

#txt_search{
 width: 95%;
 height: 22px;
 padding: 3px;
 margin-left: 5px;
 position: absolute;
 bottom: 0;
 right: 0;
 visibility: visible;
}

/* Parent Container */
.content_sel{
 position: relative;
 width: 98%;
 height: auto;
 float: left;
 margin-right: 10px;
 border: 0px solid black;
}

/* Child Text Container */
.content_sel input[type=text]{
 position: absolute;
 top: 0;
 left: 0;
 margin-bottom: 5px;
 font-family: sans-serif;
 opacity: 0;
 visibility: hidden;
 width: 150px;
 padding: 8px 15px;
}

/* Hover on Parent Container */
.content_img:hover{
 cursor: pointer;
}

.addMargin{
 width: 97% !important;
 margin-top: 30px;
 cursor: pointer;
}

.removeMargin{
 margin-top: 0px !important;
}

3. PHP

Create a new search.php for their searching entered text in the search box and returning options.

Completed Code

<?php

include "config.php";

$search_text = $_POST['search'];

if($search_text != "" || $search_text != '0'){
 $query = "SELECT * FROM department WHERE depart_name like '%".$search_text."%'";
}else{
 $query = "SELECT * FROM department";
}

$result = mysql_query($query);

$options = "<option value='0'>Select Department</option>";
while( $row = mysql_fetch_array($result) ){
 $options .= "<option value='".$row['depart_name']."'>".$row['depart_name']."</option>";
}

echo $options;

 


4. jQuery

With jQuery we perform –

Display Search Box

On click showing Textbox and positioning it above dropdown and change it to ListBox by setting size attribute.

# Displaying Searching Box

// Show Search Box
$("#sel_search").click(function(e){

 var selectedText = $("#sel_search option:selected").text();
 $("#txt_search").val(selectedText);

 // display Textbox
 $("#txt_search").css({
  opacity: 1,
  visibility: "visible"
 });

 // change Dropdown size attribute and add Class
 $(this).attr("size","5");
 $(this).addClass("addMargin");

 $("#txt_search").focus();
 e.stopPropagation();
});

On keyup sending AJAX request and replacing drop-down contents.

// Search data
$("#txt_search").keyup(function(){
 var search = $(this).val(); 
 $.ajax({
  url: 'search.php',
  type: 'post',
  data: { search:search },
  dataType: 'html',
  success:function(response){
   $("#sel_search").empty();
   $("#sel_search").append(response); 
  }
 });
});

Go to initial stage

Create a new function from resetting the layout and calling it on document click, dropdown change event.

function reset_dropdown(e){ 
 $("#sel_user").css({top:0,left:0});
 $('#sel_user').toggleClass("addMargin removeMargin");

// Hide Search Box 
 $("#txt_search").css("visibility","hidden");

// Little delaying while removing size attribute
 setTimeout(function(){
 $("#sel_search").removeAttr("size");
 },1);
}

 // Hiding Search Box
 $("#sel_search").change(function(e) {
  reset_dropdown();
 });
 
 $(document).click(function(e){
  reset_dropdown();
 });
 
 $("#txt_search").focusout(function() {  
  $("#sel_search").removeClass("addMargin"); 
 });
 
 $("#txt_search").click(function() { 
  $("#sel_search").removeClass("addMargin"); 
 });

Completed Code

$(document).ready(function(){
 
 // Show Search Box
 $("#sel_search").click(function(e){

  var selectedText = $("#sel_search option:selected").text();
  $("#txt_search").val(selectedText);

  // display Textbox 
  $("#txt_search").css({
   opacity: 1,
   visibility: "visible"
  });

  // change Dropdown size attribute and add Class 
  $(this).attr("size","5");
  $(this).addClass("addMargin");

  $("#txt_search").focus();
  e.stopPropagation(); 
 });

 // Set All Text selected on Focus
 $("#txt_search").focus(function() { 
  $(this).select(); 
 });

 // Search data
 $("#txt_search").keyup(function(){
  var search = $(this).val(); 
  $.ajax({
   url: 'search.php',
   type: 'post',
   data: { search:search },
   dataType: 'html',
   success:function(response){
    $("#sel_search").empty();
    $("#sel_search").append(response); 
   }
  });
 
 });

 // Hiding Search Box
 $("#sel_search").change(function(e) {
  reset_dropdown();
 });
 
 $(document).click(function(e){
  reset_dropdown();
 });
 
 $("#txt_search").focusout(function() { 
  // reset_dropdown(); 
  $("#sel_search").removeClass("addMargin"); 
 });
 
 $("#txt_search").click(function() { 
  $("#sel_search").removeClass("addMargin"); 
 });
 
});

// Reset layout
function reset_dropdown(e){ 
 $("#sel_user").css({top:0,left:0});
 $('#sel_user').toggleClass("addMargin removeMargin");

 // Hide Search Box 
 $("#txt_search").css("visibility","hidden");

 // Little delaying while removing size attribute
 setTimeout(function(){
  $("#sel_search").removeAttr("size");
 },1);
}

5. Demo

Click on the Dropdown and search some content.


6. Conclusion

This enables the user to quickly search item within the Dropdown list and show relevant result based on the input.

Before applying this code within your project make sure that it works according to your requirement and adjust its CSS.

If you find this tutorial useful then, feel free to share it on social media or with your friends.

Related Post

Spread the love

Be First to Comment

Leave a Reply

Your email address will not be published. Required fields are marked *