To create div elements for each select option, you can use the jQuery each() method.
Once created, you can handle click events on these divs to update the value of a hidden select element.
Note: I have added comments in my code below for better understanding.
// Creating custom select options based on original select elements
customSelect("selectOne", "customSelectOne", 1);
customSelect("selectTwo", "customSelectTwo", 0);
// Handling click event for each custom option
$(document).on("click",".selectOption", function (event) {
// Removing previously selected options
$(this).parent("div:first").find('.selectOption').removeClass('checked');
const getOptionID = $(this).data('optionid'); // Getting data-optionid value
$(this).toggleClass('checked'); // Adding/removing checked class
// Updating value of hidden select
$(this).parent("div:first").prevAll('select:first').val(getOptionID).change();
});
$('.hideShowSelect').click(function() {
$('select').toggle();
});
/*
Function to dynamically generate select options within divs
@select : selector of the select element
@div : selector of the div container for custom options
@checked : 1 for making first div checked, 0 for not
*/
function customSelect(select, div, checked) {
// Looping through each option in the original select element
$('select[name="' + select + '"] option').each(function(index) {
// Checking if the first option needs to be pre-selected
const checkFirstOption = (index === 0 && checked === 1 ? ' checked' : '');
const optionVal = $(this).val(); // Getting option value
// Creating a div for each option with corresponding data-value attribute
$('.' + div).append('<div class="selectOption'+ checkFirstOption +'" data-optionid="' + optionVal + '">' + optionVal + '</div>');
});
}
#myform {
max-width:450px;
margin-top:25px;
}
#myform select {
display:none;
}
#myform .selectOption {
color:#141414;
cursor:pointer;
display: inline-block;
border: 1px solid #bebebe;
padding:15px 17.5px;
border-radius:2.5px;
margin:5px;
transition: all 0.3s ease-out;
}
#myform .selectOption.checked {
border: 1px solid #111;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="myform">
<select name="selectOne">
<option value="70A">70A</option>
<option value="70B">70B</option>
<option value="70C">70C</option>
<option value="75A">75A</option>
<option value="75B">75B</option>
<option value="75C">75C</option>
</select>
<div class="customSelectOne"></div>
<select name="selectTwo">
<option value="80B">80B</option>
<option value="80C">80C</option>
<option value="80D">80D</option>
<option value="85B">85B</option>
<option value="85C">85C</option>
<option value="85D">85D</option>
</select>
<div class="customSelectTwo"></div>
</form>
<p><a href="#" class="hideShowSelect">Hide / show select</a></p>