Can someone please help me with an issue I am facing? When I try to focus and select from the up and down arrow keys, it is not working as expected.
Below is a snippet of my code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link href="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="b8cbddd4dddbcc8af88c9689968895daddccd99689">[email protected]</a>/dist/css/select2.min.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="1665737a737562245622382738263b747362773827">[email protected]</a>/dist/js/select2.min.js"></script>
<style>
.highlight {
background-color: yellow;
}
</style>
</head>
<body>
<div style="margin-left: 500px; margin-top: 200px;">
<form action="" method="post">
<select id='country' name="country" style='width: 200px;'>
<optgroup label='div1'>
<option value='1'>India</option>
<option value='2'>America</option>
</optgroup>
<optgroup label='div2'>
<option value='3'>Pakistan </option>
<option value='4'>Afghanistan</option>
</optgroup>
</select>
<br/>
<input type="submit" name="save" value="submit">
</form>
</div>
<script>
$(document).ready(function(){
$("#country").select2();
$("#country").on("select2:open", function (e) {
// Highlight the initially selected option
highlightSelected();
});
$("#country").on("select2:select", function (e) {
// Highlight the selected option when selected via mouse
highlightSelected();
});
// Listen for keydown events
$("#country").on("keydown", function (e) {
var currentOption = $(this).find(":selected");
var highlightedOption;
if (e.which === 38) { // Up arrow
highlightedOption = currentOption.prev();
} else if (e.which === 40) { // Down arrow
highlightedOption = currentOption.next();
}
if (highlightedOption.length > 0) {
$(this).find("option").removeClass("highlight");
highlightedOption.addClass("highlight");
}
});
function highlightSelected() {
var selectedOption = $("#country").find(":selected");
$("#country").find("option").removeClass("highlight");
selectedOption.addClass("highlight");
}
});
</script>
</body>
</html>
I have been trying to get the functionality to work where I can use the up and down arrow keys on the keyboard when focusing on elements in the dropdown menu.
...........................................................................................................................................