DEV Community

Cover image for HTML Dropdown form with a search bar with dynamically populated list items for SQL database
wpyoh
wpyoh

Posted on

HTML Dropdown form with a search bar with dynamically populated list items for SQL database

Many websites have been using HTML forms to get user data or display results based on input value submitted by the form. My requirement was an HTML dropdown form with search functionality with I successfully implemented on my website. The search bar is really useful to search through a dropdown list of 100+ items as implemented in my project FPS Calculator.

I was able to get the search functionality to work by using JavaScript that filters through all the items in the list by their name. Referring to many YouTube videos I was able to get the result needed.

This form search works on a simple JavaScript function which does not have any external API call and is executed in the browser. Hence the performance is not compromised and page load speeds are super fast. The JavaScript code is given below:

const selected = document.querySelector(".selected");
const optionsContainer = document.querySelector(".options-container");
const searchBox = document.querySelector(".search-box input");

const optionsList = document.querySelectorAll(".option");

selected.addEventListener("click", () => {
  optionsContainer.classList.toggle("active");

  searchBox.value = "";
  filterList("");

  if (optionsContainer.classList.contains("active")) {
    searchBox.focus();
  }
});

optionsList.forEach(o => {
  o.addEventListener("click", () => {
    selected.innerHTML = o.querySelector("label").innerHTML;
    optionsContainer.classList.remove("active");
  });
});

searchBox.addEventListener("keyup", function(e) {
  filterList(e.target.value);
});

const filterList = searchTerm => {
  searchTerm = searchTerm.toLowerCase();
  optionsList.forEach(option => {
    let label = option.firstElementChild.nextElementSibling.innerText.toLowerCase();
    if (label.indexOf(searchTerm) != -1) {
      option.style.display = "block";
    } else {
      option.style.display = "none";
    }
  });
};
Enter fullscreen mode Exit fullscreen mode

The JavaScript targets the div class in CSS. I have also attached a sample style.css I used in my project so mapping my div class target in JavaScript will be easier for you guys.

/* Searchbox */

.search-box input {
  width: 100%;
  padding: 12px 16px;
  font-family: "Roboto", sans-serif;
  font-size: 16px;
  position: absolute;
  border-radius: 8px 8px 0 0;
  z-index: 100;
  border: 8px solid #2f3640;

  opacity: 0;
  pointer-events: none;
  transition: all 0.4s;
}

.search-box input:focus {
  outline: none;
}

.select-box .options-container.active ~ .search-box input {
  opacity: 1;
  pointer-events: auto;
}
Enter fullscreen mode Exit fullscreen mode

Using the above CSS and JavaScript in an HTML dropdown form, a search bar with search functionality can be implemented easily.

HTML Dropdown form design

The HTML form uses the radio input option to get the value selected. Since radio input type is used, multiple item selection is not possible.

The radio select options are placed inside a div with a name container. In CSS the container class is designed such that it acts as a scrollable list with a scroll bar. This is coupled with the search box bar mentioned earlier.

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
</head>
  <body>
    <div class="container">
      <h2>Video Category</h2>

      <div class="select-box">
        <div class="options-container">
          <div class="option">
            <input
              type="radio" class="radio" id="automobiles" name="category"/>
            <label for="automobiles">Automobiles</label>
          </div>

          <div class="option">
            <input type="radio" class="radio" id="film" name="category" />
            <label for="film">Film & Animation</label>
          </div>
</div>

        <div class="selected">
          Select Video Category
        </div>

        <div class="search-box">
          <input type="text" placeholder="Start Typing..." />
        </div>
      </div>
    </div>
  </body>
</html>
Enter fullscreen mode Exit fullscreen mode

The above HTML code uses the radio select input type. For the search box bar a simple input type text is used in a div with class search-box. The search-box CSS is designed along with the JavaScript mentioned above to implement the search functionality.

PHP code to dynamically get list item from SQL table in database

For this project, WordPress is used. Hence the default WordPress database functions such as $wpdb is used. The form select input type div is wrapped in a for loop as shown in the PHP code below.

<div class="formcontainer">
      <form action="" method="GET">
      <div class="select-box">
        <div class="options-container">
          <?php
          foreach( $result as $value ) { ?>
          <div class="option">
            <input
              type="radio" class="radio" id="<?php echo $value->game_name; ?>" name="game" value="<?php echo $value->game_name; ?>" />
            <label for="<?php echo $value->game_name; ?>"><?php echo $value->game_name; ?></label>
            </div>
            <?php
            }
          ?>
        </div>
Enter fullscreen mode Exit fullscreen mode

The table column containing the list items are selected using $wpdb function and SQL commands. The array from the SQL command is stored in the $result variable. The the for loop the $result $value condition is used. The name in the radio option is displayed using php echo $value with the database table column name.

The for loop repeated the radio input type for each column cell in the database. Hence dynamically displaying all items in a table column. In future if the column is updated in the SQL database table, the for loop dynamically displays the newly entered values in the column.

I have attached all references i used to develop this dropdown form below:
Youtube video - https://www.youtube.com/watch?v=VZzWzRVXPcQ&t=183s
GitHub - https://github.com/Godsont/Custom-Select-Box-with-Search

Top comments (1)

Collapse
 
chamanos profile image
chamanoS

I have been working on a similar feature and this article helped me a lot. Thanks.