Sitemap / Advertise

Information



Tags



Share

How to code a select form element from scratch in CSS and jQuery

Advertisement:


read_later

Read Later

Keywords



Keywords



read_later

Read Later

Information

Tags

Share





Advertisement

Advertisement




Definition

If you do not want to use the default version of select and option elements embedded in browsers, you can create a new one from scratch as I will show you down below. To manage that, we just need to surmount two problems; creating a selectable option list and collecting the choice after selecting for further usages, such as form submitting.

Code

Create a container by using a section element and a header by using a span element.

For displaying options like a select element, use list elements in a hidden sub-section element.

To customize each list element, use li:nth-of-type(odd) and li:nth-of-type(even) properties.

To change the arrow upside-down and make visible the options bar, use jQuery toggle() and toggleClass() methods as well-explained on the code part.

To make the container feature like a select element when any list element clicked as options, use the on() function in jQuery to obtain the text that of the selected element in order to either display or send it as a form value, as depicted below.


******** CSS ********

.select{position:relative;display:inline-block;width:auto;height:auto;background-color:DodgerBlue;user-select:none;}
.select:hover{background-color:#0066cc;}
.select span{color:white;padding-left:10px;padding-right:10px;cursor:pointer;font-weight:bold;font-size:15px;}
.select section{display:none;}
.select li:nth-of-type(odd), .select li:nth-of-type(even){background-color:#4da6ff;cursor:pointer;list-style-type:none;padding-left:10px;color:white;font-size:13px;font-weight:bold;}
.select li:nth-of-type(even){background-color:#80bfff;}
.select li:hover{background-color:#0066cc;transition:0.1s;}

********

******** JavaScript(jQuery) ********

$(".select").on("click", "span", function(){
$(this).parent().find("section").toggle();
$(this).parent().find("i").toggleClass("fas fa-sort-up fas fa-sort-down");
});

$(".select").on("click", "li", function(){
$(this).parent().hide();
$(this).parent().parent().find("i").toggleClass("fas fa-sort-up fas fa-sort-down");
$("#value").html("Selected: " + $(this).text());
});

********

******** HTML ********

<section class="select"><span>Select Plants <i class="fas fa-sort-down"></i></span>
<section>
<li>Annuals</li>
<li>Bulbs</li>
<li>Cactus</li>
<li>Climbers</li>
<li>Conifers</li>
<li>Ferns</li>
<li>Fruits</li>
<li>Herbs</li>
<li>Perennials</li>
<li>Roses</li>
<li>Shrubs</li>
<li>Trees</li>
</section>
</section>

********

Result:

Select Plants
  • Annuals
  • Bulbs
  • Cactus
  • Climbers
  • Conifers
  • Ferns
  • Fruits
  • Herbs
  • Perennials
  • Roses
  • Shrubs
  • Trees
  • Please Select...