To do the simple dropdown search using JQquery, please follow below code, In this sample, I have used
select2 jQuery plugin to create dropdown with a search box.
Please include select2.min.css and select2.min.js with jQuery library in the head section as follows:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.8/css/select2.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.8/js/select2.min.js"></script>
Create a dropdown element and add few sample options and also add a button to read the selected dropdown value and dispay in the result div.
<select id="selectColor" style="width: 200px;" tabindex="-1" class="select2-hidden-accessible" aria-hidden="true">
<option value="0">-- Select Color --</option>
<option value="#9400D3">Violet</option>
<option value="#4B0082">Indigo</option>
<option value="#0000FF">Blue</option>
<option value="#00FF00">Green</option>
<option value="#FFFF00">Yellow</option>
<option value="#FF7F00">Orange</option>
<option value="#FF0000">Red</option>
</select>
<input type="button" value="Seleted Color" id="btnSelectColor">
<div id="result">Hexa Code : , Color Name : </div>
Please find below the JQuery script
<script >
$(document).ready(function () {
// Initialize select2
$("#selectColor").select2();
// Read selected option
$('#btnSelectColor').click(function () {
var colorName = $('#selectColor option:selected').text();
var colorHexaCode = $('#selectColor').val();
$('#result').html("Hexa Code : " + colorHexaCode + ", Color Name : " + colorName);
});
}); <
/script>
Please find the demo below and
click here to download the sample html file.