I have an input field that is to be populated from a dropdown menu with a list of options, but the list can be very long. I want the user to be able to simply start typing a letter or two and the field to pre-populate or provide a suggestion with the first partial match in the list, then simply Enter to select it. Is there a way to do this?
Right now, the user has to scroll down the menu and select, but it’s not a great experience for longer lists.
You could try filtering the list of options by what they have typed in the input. I don’t think that would solve the enter to select it. Another option which I have done before is to create a custom dropdown component that has an input and a list of options underneath it I did this so that people could create there own new responses rather then selecting from the dropdown.
Here’s how I solved this in case anyone finds it useful:
I wrote a Java Script to trigger (on change) search all the values in a list of objects, as the user is typing, and create a modified list of objects with the key-values I need to display in my list (empty to start).
// Here's my JavaScript
const searchString = <input variable>
const jsonArray = <array to filter on>
const results = [];
// If the search string is empty, return an empty array
if (searchString.trim() === "") {
return [];
}
// Iterate over each object in the jsonArray
for (let i = 0; i < jsonArray.length; i++) {
const obj = jsonArray[i];
let matchFound = false;
const resultObj = {};
// Iterate over each key in the current object
for (const key in obj) {
if (obj.hasOwnProperty(key)) {
// Check if the value of the current key contains the search string
if (String(obj[key]).toLowerCase().includes(searchString.toLowerCase())) {
// If there's a match, add the id, name, and legal_des to resultObj
if (obj.hasOwnProperty("id")) {
resultObj.id = obj.id;
}
if (obj.hasOwnProperty("name")) {
resultObj.name = obj.name;
}
if (obj.hasOwnProperty("legal_des")) {
resultObj.legal_des = obj.legal_des;
}
matchFound = true;
// No need to continue searching through other keys
break;
}
}
}
// If a match was found, add resultObj to the results array
if (matchFound) {
results.push(resultObj);
}
}
return results;
I still don’t have a solution for selecting the top value and using keyboard to navigate down the list so that I can enter to select it. I need to spend more time on that, for now this will do.
Cool solution! But i think this is already achievable from the select element, by turning on searchable? I can search for “or” hit enter and “orange” will be selected.