Creating a Custom Select Box using CSS and JavaScript Tutorial

In this tutorial, you can learn how to create a simple Custom Select Box with Search Bar using CSS and JavaScript. The tutorial aims to provide students and beginners with a reference to learn with for creating a useful web application or website component. Here, I will be providing a sample web page script that demonstrates the creation of a Custom Select Box with a Search Bar.

What is Select Box?

The Select Box is an HTML Element used to create a drop-down list. It is usually used in a form with an input field that allows the user to select a value from multiple options. In HTML, we can simply create a select box using <select> tag, and the options are listed inside this tag enclosed in <option> tag for each item.

How to Create a Custom Select Box with Search Bar?

The Custom Select Box with Search Bar can be easily achieved using CSS and JavaScript. To do that, we need to create a new element that will represent the select box and hide the original select box. After that, we can design the select box using the CSS code. Then, using some JavaScript event listeners, methods, built-in APIs, and functions, we can make the custom select box functional and update the hidden original box value with the item selected on the custom one. Check out the sample web page script that I created and provided below to understand more about creating the custom select box.

Sample Web Page

The scripts below result in a simple web page that contains a custom select box. The custom select box contains a search feature that allows the user to search items using keywords. When the item is selected, the custom select box selected item text will be updated and the hidden select element will be also updated.

HTML

Here's the HTML file script of the page layout and select box element.

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <meta charset="UTF-8">
  4. <meta http-equiv="X-UA-Compatible" content="IE=edge">
  5. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  6. <title>CSS and JS - Custom Select Box</title>
  7. <link rel="preconnect" href="https://fonts.googleapis.com">
  8. <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
  9. <link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Material+Symbols+Outlined:opsz,wght,FILL,[email protected],100..700,0..1,-50..200" />
  10. <link rel="stylesheet" href="style.css">
  11. <link rel="stylesheet" href="custom-select.css">
  12. </head>
  13. <div id="wrapper">
  14. <div class="page-title">Creating a Simple Select Box using CSS and JavaScript</div>
  15. <hr style="margin:auto; width:25px">
  16. <div id="select-wrapper">
  17. <div>
  18. <select name="sampleSelect" id="sampleSelect">
  19. <option>JavaScript</option>
  20. <option>Python</option>
  21. <option>Go</option>
  22. <option>Java</option>
  23. <option>Kotlin</option>
  24. <option>PHP</option>
  25. <option>C#</option>
  26. <option>Swift</option>
  27. <option>Ruby</option>
  28. <option>C and C++</option>
  29. <option>Matlab</option>
  30. <option>TypeScript</option>
  31. <option>Scala</option>
  32. <option>HTML</option>
  33. <option>CSS</option>
  34. </select>
  35. </div>
  36. </div>
  37. </div>
  38. <script src="custom-select.js"></script>
  39. </body>
  40. </html>

Page Layout Stylesheet

Next, here's the CSS script that contains the code for the design of the page layout.

  1. @import url('https://fonts.googleapis.com/css2?family=Courgette&family=Secular+One&display=swap" rel="stylesheet');
  2. :root{
  3. --secular-font: 'Secular One', sans-serif;
  4. }
  5. *{
  6. box-sizing: border-box;
  7. }
  8. body *{
  9. font-family: 'Rubik', sans-serif;
  10. }
  11. /**
  12.   Page Design
  13.   */
  14. body,
  15. html{
  16. height: 100%;
  17. width: 100%;
  18. margin: 0;
  19. padding: 0;
  20. }
  21. body{
  22. background-color: #B9F3E4;
  23. }
  24. /* Page Wrapper */
  25. #wrapper{
  26. width: 100%;
  27. padding: 3em 5em;
  28. }
  29. .page-title{
  30. font-size: 2.5rem;
  31. font-weight: 500;
  32. color: #fff;
  33. letter-spacing: 3px;
  34. font-family: var(--secular-font);
  35. text-align: center;
  36. text-shadow: 0px 0px 3px #2020208c;
  37. }
  38. /* Select box Wrapper */
  39. #select-wrapper{
  40. position: relative;
  41. width: 300px;
  42. margin:auto;
  43. margin-top:3em
  44. }

Custom Select Box Stylesheet

Next, here's the CSS script that contains the code for the design of the custom select box.

  1. .custom-select-box-parent{
  2. position: relative;
  3. width: 100%;
  4. }
  5. .custom-select-box-container{
  6. width: 100%;
  7. display: flex;
  8. flex-wrap: wrap;
  9. padding:.35em .5em;
  10. background-color: #ffffff;
  11. border:1px solid #eeeeee;
  12. min-height: 1.2em;
  13. justify-content: space-between;
  14. box-shadow: 1px 1px 3px #3d3d3d52;
  15. cursor: pointer;
  16. }
  17. .custom-select-box-selected{
  18. width: 90%;
  19. font-size: .9rem;
  20. font-weight: 400;
  21. }
  22.  
  23. .custom-select-box-dd-icon{
  24. width: 10%;
  25. transition: all .3s ease;
  26. position:relative;
  27. }
  28. .custom-select-box-dd-icon:before{
  29. content: "\25BE";
  30. position:absolute;
  31. top:0;
  32. transform: translateX(50%);
  33. }
  34. .custom-select-box-parent.show .custom-select-box-dd-icon{
  35. transform: rotate(180deg);
  36. }
  37.  
  38.  
  39. .custom-select-box-options-container{
  40. width: 100%;
  41. position: absolute;
  42. background-color: #fff;
  43. border:1px solid #e7e7e7;
  44. margin-top:.5em;
  45. box-shadow:0px 0px 5px #2727272d;
  46. display: none;
  47. }
  48. .custom-select-box-parent.show .custom-select-box-options-container{
  49. display: block;
  50. }
  51. .custom-select-box-search{
  52. position: relative;
  53. width: 100%;
  54. padding: .35em;
  55. }
  56. .custom-select-box-search:before {
  57. content: "";
  58. width: 30px;
  59. height: calc(100% - 0.7em);
  60. position: absolute;
  61. z-index: 2;
  62. background: transparent url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='16' height='16' class='bi bi-search' viewBox='0 0 16 16'%3E%3Cpath d='M11.742 10.344a6.5 6.5 0 1 0-1.397 1.398h-.001c.03.04.062.078.098.115l3.85 3.85a1 1 0 0 0 1.415-1.414l-3.85-3.85a1.007 1.007 0 0 0-.115-.1zM12 6.5a5.5 5.5 0 1 1-11 0 5.5 5.5 0 0 1 11 0z'%3E%3C/path%3E%3C/svg%3E") no-repeat center;
  63. }
  64. .custom-select-box-search-box{
  65. width: 100%;
  66. padding:.35em 0.35em .35em 30px;
  67. font-size: .9rem;
  68. color:#333333;
  69. outline:none;
  70. border:1px solid #bbbbbb;
  71. }
  72. .custom-select-box-search-box:focus{
  73. border-color: #a0a0a0;
  74. box-shadow: 0px 0px 5px #2727272d;
  75. }
  76. .custom-select-box-options{
  77. position:relative;
  78. margin-top:.35em;
  79. width: 100%;
  80. max-height:35vh;
  81. overflow-y: auto;
  82. padding:.35em .2em
  83. }
  84. /* width */
  85. .custom-select-box-options::-webkit-scrollbar {
  86. width: 5px;
  87. }
  88.  
  89. /* Track */
  90. .custom-select-box-options::-webkit-scrollbar-track {
  91. background: #f1f1f1;
  92. }
  93.  
  94. /* Handle */
  95. .custom-select-box-options::-webkit-scrollbar-thumb {
  96. background: #888;
  97. border-radius: 5px;
  98. }
  99.  
  100. /* Handle on hover */
  101. .custom-select-box-options::-webkit-scrollbar-thumb:hover {
  102. background: #555;
  103. }
  104. .custom-select-box-item{
  105. background: #fff;
  106. width: 100%;
  107. padding: .35em .5em;
  108. border:1px solid #e9e9e9;
  109. cursor: pointer;
  110. }
  111. .custom-select-box-item:hover,
  112. .custom-select-box-item[data-selected="true"]{
  113. background: #e6e6e6;
  114. }
  115.  

JavaScript

Next, here's the JavaScript object-oriented script that was created that creates the custom select box and handles the component's functionality codes.

  1. /** Custom Select Box */
  2. class CustomSelectBox{
  3. /** Parent Element */
  4. selectParentEl = document.createElement('div')
  5. /** Custom Select Box HTML */
  6. selectHTML = `<div class="custom-select-box-container">
  7. <div class="custom-select-box-selected">Please Select here</div>
  8. <span class="custom-select-box-dd-icon"></span>
  9. </div>
  10. <div class="custom-select-box-options-container">
  11. <div class="custom-select-box-search">
  12. <input type="search" class="custom-select-box-search-box">
  13. </div>
  14. <div class="custom-select-box-options">
  15. </div>
  16. </div>`;
  17.  
  18. optionItemEl = document.createElement('div')
  19. constructor(){
  20. this.selectParentEl.classList.add('custom-select-box-parent')
  21. this.selectParentEl.innerHTML = this.selectHTML
  22. this.optionItemEl.classList.add('custom-select-box-item')
  23. this.selectParentEl.addEventListener('click', this.showSelect.bind(this))
  24. }
  25. init(el){
  26. /** Initialize Custo Select Box */
  27. el.style.display = `none`;
  28. el.after(this.selectParentEl)
  29. var selOpts = el.querySelectorAll('option')
  30.  
  31. /** Append Items */
  32. selOpts.forEach(option => {
  33. var optEl = this.createElfromOption(option)
  34. this.selectParentEl.querySelector('.custom-select-box-options').appendChild(optEl)
  35. })
  36.  
  37. /** Add Click Event for Selecting Item */
  38. this.selectParentEl.querySelectorAll('.custom-select-box-item').forEach(item =>{
  39. item.addEventListener('click', this.selectItem.bind(this, item, el))
  40. })
  41.  
  42. /** trigger Search */
  43. this.selectParentEl.querySelector('.custom-select-box-search-box').addEventListener('input', this.selectSearch.bind(this))
  44. }
  45.  
  46. /** Show custom option block */
  47. showSelect(){
  48. this.selectParentEl.classList.add('show')
  49. document.addEventListener('click', this.closeSelect.bind(this))
  50.  
  51. }
  52. /** close custom option block */
  53. closeSelect(e){
  54. var selectBoxOptC = this.selectParentEl.outerHTML
  55. if(selectBoxOptC.includes(e.target.outerHTML) == false){
  56. this.selectParentEl.classList.remove('show')
  57. document.removeEventListener('click', this.closeSelect)
  58. this.resetSearch()
  59. }
  60. }
  61. /** Search Item */
  62. selectSearch(){
  63. var search = this.selectParentEl.querySelector('.custom-select-box-search-box').value
  64. this.selectParentEl.querySelectorAll('.custom-select-box-item').forEach(item =>{
  65. if((item.innerText.toLowerCase()).includes(search.toLowerCase()) == true){
  66. item.style.display = 'block'
  67. }else{
  68. item.style.display = 'none'
  69. }
  70. })
  71. }
  72. /** Reset Search box */
  73. resetSearch(){
  74. this.selectParentEl.querySelector('.custom-select-box-search-box').value = '';
  75. this.selectSearch()
  76. }
  77.  
  78. /** Selected Item function */
  79. selectItem(item, el){
  80. var val = item.dataset.value
  81. var txt = item.innerText
  82. if(this.selectParentEl.querySelector('.custom-select-box-item[data-selected="true"]') !== null)
  83. this.selectParentEl.querySelector('.custom-select-box-item[data-selected="true"]').removeAttribute('data-selected')
  84. item.dataset.selected = 'true'
  85. if(el.querySelector('option[selected]') !== null)
  86. el.querySelector('option[selected]').removeAttribute('selected')
  87.  
  88. if(el.querySelector('option') !== undefined){
  89. el.querySelectorAll('option').forEach(option =>{
  90. if(!!option.dataset.value){
  91. if(option.dataset.value == val)
  92. option.setAttribute('selected', true);
  93. }else{
  94. if(option.innerText == val)
  95. option.setAttribute('selected', true);
  96. }
  97. })
  98. }
  99. this.selectParentEl.querySelector('.custom-select-box-selected').innerText = txt
  100. setTimeout(()=>{
  101. this.selectParentEl.classList.remove('show')
  102. document.removeEventListener('click', this.closeSelect.bind(this))
  103. this.resetSearch()
  104. },100)
  105.  
  106. }
  107.  
  108. /** Create the Item form Option */
  109. createElfromOption(option){
  110. var val = option.dataset.value || option.innerText
  111. var txt = option.innerText
  112. var item = this.optionItemEl.cloneNode(true)
  113. item.dataset.value= val
  114. item.innerText= txt
  115. return item
  116. }
  117. }

Initialize Custom Select Box

Lastly, here's the JS script that initializes or converts the HTML select element to a custom select box.

  1. var customSelect = new CustomSelectBox()
  2. customSelect.init(document.getElementById('sampleSelect'))

Snapshots

The following images or snapshot is the overall result of the web page scripts that I provided above.

Custom Select Box

Custom Select Box using CSS and JS

Option Block/Container is shown

Custom Select Box using CSS and JS

When Searching Item

Custom Select Box using CSS and JS

DEMO

Custom Select Box using CSS and JS

There you go! I have also provided the source code zip file of the sample web page on this site and it is free to download. To download the file, you can simply click the download button located below this tutorial's content. Feel free to download and do some experiments.

That's it! I hope this Creating a Custom Select Box using CSS and JavaScript Tutorial will help you with what you are looking for and will be helpful for your current and future web application projects.

Explore more on this website for more Tutorials and Free Source Codes.

Happy Coding =)

Comments

Submitted bykouakou francis (not verified)on Mon, 10/30/2023 - 19:09

Hello Master, Thank you very much for this great job you have done. This partly answers my problem. I use it to save countries in my database. the recording is fine. on the other hand I would like to make modifications to the registered countries (example change country). My problem is I can't assign the first value to the select. how to automatically select a country that comes from a mysql database for a modification? Help me please

Add new comment