Autocomplete list Selection using Key Up/Down in Textbox and Scroll should move in asp.net c#
When pressing the up or down keys in an autocomplete textbox, if dropdown options are available, the selection should move through the values, and the scroll should adjust accordingly, moving from top to bottom or bottom to top based on key presses.
TextBox control
<div id='announce' class='visually-hidden' aria-live="assertive"></div>
<input id="sp_smbl_srch" runat="server" type="text" oncopy="javascript:return false;" onpaste="javascript:return false;"
oncut="javascript:return false;" oninput="this.value = this.value.replace(/[^a-zA-Z0-9&]/g, '').toUpperCase();"
placeholder="Search" aria-label="search" aria-describedby="search1"
value="NIFTY" autocomplete="off" class="form-control bg-transparent border-0" />
<span class="input-group-text border-0 bg-transparent" id="search1">
<i class="bi bi-search"
style="cursor: pointer"></i>
</span>
<%-- symbols will add to this div --%>
<div class="strategy_mainscriptdiv" style="display: none;">
</div>
</div>
For example, if you type "nifty" in the textbox, the related suggestions will appear in a dropdown.
<div class="strategy_mainscriptdiv" style="display: block;"><div id="res" role="listbox" tabindex="-1"><div role="option" tabindex="-1" id="suggestion-1" class="highlight">NIFTY</div><div role="option" tabindex="-1" id="suggestion-2">BANKNIFTY</div><div role="option" tabindex="-1" id="suggestion-3">FINNIFTY</div><div role="option" tabindex="-1" id="suggestion-4">MIDCPNIFTY</div><div role="option" tabindex="-1" id="suggestion-5">NIFTYNXT50</div></div></div>
As shown in the image the scroll is not moving if I press the key up / down but the value selection is happening.
Here, I'm utilizing the class strategy_mainscriptdiv
.
.strategy_mainscriptdiv {
position: absolute;
height: 100px;
left: 0;
top: 44px;
background-color: #f6f6f6;
display: none;
font-size: 13px;
overflow-x: hidden;
overflow-y: auto;
padding: 8px;
z-index: 99;
width: 220px;
-webkit-box-shadow: 0 0 10px #fff;
box-shadow: 0 8px 18px #a2a2a2;
}
Here is the logic for my Autocomplete
textbox implemented using jQuery.
function autocompletetextbox(n) {
var suburbs = [];
var cls, id, divid;
var sa = "";
var dynclas = "";
var dyndivid = ""
var dynsa = "";
var counter = 1;
/*Array of keys used for the keyboard interactions*/
var keys = {
LEFT: 37,
RIGHT: 39,
UP: 38,
DOWN: 40
};
var lastKeyPressed; // Variable to track the last pressed key
$("#sb_smbl_srch").on("keydown", function (event) {
lastKeyPressed = event.which || event.keyCode;
doKeypressEvent(keys, event);
});
//auto complete textbox
$("#sb_smbl_srch").autocomplete({
source: function (request, response) {
var param = { usersymbl: $('#sp_smbl_srch').val() }, cls = ".strategy_mainscriptdiv", id = "#sp_smbl_srch", divid = "#announce";
if (request.term && request.term.length >= 2 && lastKeyPressed !== keys.UP && lastKeyPressed !== keys.DOWN
&& lastKeyPressed !== keys.LEFT && lastKeyPressed !== keys.RIGHT) {
$.ajax({
url: "Model/regularajaxcalls.aspx/GetSBSymbols",
data: JSON.stringify(param),
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
dataFilter: function (data) {
return data;
},
success: function (data) {
if (data.d.length == 0) {
if (sa == "up")
$(cls).empty(), $("#second_own_index").val(''), $(cls).append("<div class='nodata text-center'>Sorry! No Match Found !</div>"), $(cls).slideDown(), $(".second_own_scriptdiv").slideUp();
else
$(cls).empty(), $("#own_index").val(''), $(cls).append("<div class='nodata text-center'>Sorry! No Match Found !</div>"), $(cls).slideDown(), $(".own_scriptdiv").slideUp();
}
else {
suburbs = [];
response($.map(data.d, function (item) {
suburbs.push(item);
}))
$(cls).empty();
////For testing use this
//var suburbs = ["NIFTY", "BANKNIFTY", "FINNIFTY", "MIDCPNIFTY", "NIFTYNXT50"];
doSearch(suburbs, cls, id, n, divid, sa); //Calling the Symbol Display Method
}
},
error: function (err) {
console.log(err.responseText);
}
});
}
else {
// Do nothing if the entered value does not match the pattern
return false;
}
},
minLength: 2 //This is the Char length of inputTextBox
});
}
/*This function performs the search based on the users input, and builds the list of suggestions*/
function doSearch(suburbs, cls, id, n, divid, sa) {
/*If statement to start the search only after 2 characters have been enter. This number can be higher or lower depending on your preference*/
if ($(id).val().length >= 2) {
/*Make sure we have at least 1 suggestion*/
if (suburbs.length >= 1) {
/*Start things fresh by removing the suggestions div and emptying the live region before we start*/
if (sa == "up")
$("#second_own_index").val(''), $(".second_own_scriptdiv").slideUp();
else
$("#own_index").val(''), $(".own_scriptdiv").slideUp();
$("#res").remove();
$(divid).empty();
$(cls).slideDown();
/*Create the listbox to store the suggestions*/
$(cls).append('<div id="res" role="listbox" tabindex="-1"></div>');
counter = 1;
}
/*Appending the symbols to div class*/
$.each(suburbs, function (index, value) {
if (counter <= 100) {
$("#res").append("<div role='option' tabindex='-1' id='suggestion-" + counter + "'>" + value + "</div>");
counter = counter + 1;
}
});
/*Count the number of suggestions available and annouce to screen readers via live region */
var number = $("#res").children('[role="option"]').length
if (number >= 1) {
$(divid).text(+number + " suggestions found" + ", to navigate use up and down arrows");
}
// Reset highlighting when suggestions are re-rendered
$("#res").children('[role="option"]').removeClass('highlight');
var suburbs = [];
}
else {
/*If no results make sure the list does not display*/
$("#res").remove();
$(divid).empty();
$(cls).slideUp();
}
//Bind click event to suggestions in results
$("#res").on("click", "div", function () {
/*When an option is clicked, copy it's text into the input field, then close and remove the list of suggestions*/
$(id).val($(this).text());
$("#res").remove();
$(divid).empty();
$(cls).slideUp();
}
counter = 1;
});
}
To implement this functionality, I wrote the doKeypressEvent(keys, event)
function. However, when the function is called, it only highlights the value but doesn't move the scroll up or down.
function doKeypressEvent(keys, event) {
var $res = $("#res"); // The dropdown container
var $options = $res.find('div[role="option"]'); // All suggestions
var $active = $options.filter('.highlight'); // The currently highlighted item
var currentIndex = $options.index($active); // Index of highlighted item
// Handle UP key
if (event.keyCode === keys.UP) {
event.preventDefault();
if (currentIndex > 0) {
$active.removeClass('highlight'); // Remove highlight from current
$options.eq(currentIndex - 1).addClass('highlight'); // Highlight previous
}
}
// Handle DOWN key
else if (event.keyCode === keys.DOWN) {
event.preventDefault();
if (currentIndex < $options.length - 1) {
$active.removeClass('highlight'); // Remove highlight from current
$options.eq(currentIndex + 1).addClass('highlight'); // Highlight next
} else if (currentIndex === -1) {
// If nothing is highlighted yet, highlight the first item
$options.eq(0).addClass('highlight');
}
}
// Handle ENTER key to select the highlighted option
else if (event.keyCode === 13) {
event.preventDefault();
if ($active.length > 0) {
// Simulate click on the highlighted item to select it
$active.click();
}
}
}
.highlight {
background-color: #dcdcdc; /* Or any color for highlight */
cursor: pointer;
}
Suggest me where I did the mistake and how to achieve this?