I’m working on building an email input field that works like Gmail’s recipient selector. I want users to be able to type either a person’s name or their email address and get matching results.
Right now I have basic jQuery autocomplete working with this setup:
The goal is to let users search by typing either “John” or “john.smith” and still find the right contact. How can I modify the autocomplete to search through both the name part and the email part of each entry? I want the search to work no matter which part of the contact info they start typing.
You’ll need to override the default matching by creating a custom source function. Parse your contact strings to grab both the display name and email, then search both fields. Here’s what worked for me:
$("#emailField").autocomplete({
source: function(request, response) {
var matcher = new RegExp($.ui.autocomplete.escapeRegex(request.term), "i");
var results = contactList.filter(function(contact) {
var nameMatch = contact.match(/^"([^"]+)"/)[1];
var emailMatch = contact.match(/<([^>]+)>/)[1];
return matcher.test(nameMatch) || matcher.test(emailMatch);
});
response(results);
},
multiple: true,
mustMatch: true,
autoFill: true
});
This grabs the name from between quotes and email from angle brackets, then checks user input against both. The regex handles your contact format without issues.
Here’s what I did instead - preprocess your contact data into a searchable format when the page loads. I had the same problem and found it way more efficient to normalize everything upfront instead of running regex on every keystroke. Just create an array where each contact object has separate name and email properties, then use jQuery’s filter method to search both fields at once. You’ll dodge the performance hit from regex parsing during user input and can add cooler features like partial word matching or fuzzy search. The preprocessing overhead is nothing compared to real-time parsing, especially with bigger contact lists.
try a custom source function instead of just using contactList. split each contact and search both name and email parts. the autocomplete widget can do custom matching pretty easily.