Reputation: 1760
I have a list of records displayed on the screen, email records is selectable so i user can see more details of that records.
<ul>
<li data-email="[email protected]">Dave</li>
<li data-email="[email protected]">Jess</li>
<li data-email="[email protected]">Jay</li>
<li data-email="[email protected]">Mary</li>
<li data-email="[email protected]">James</li>
</ul>
Please note, this data was just made up on the spot, i probably should have used better email address....
I have a search box on this page that allows a user to type in a search string and i want my app to search through this list of records and look for any instance of the input string on Name and email addresses.
I have a function that fires when a user enters a search string but can't figure out the best way to search through these records. I can achieve this use an AJAX call to a php file that would just run a jquery with that search sting but i wanted to try and do it on the client side of things.
So does anyone know of a good way of doing this in Javascript/JQuery or would it be better practice to just do the Mysql query?
This is the JS code i have, this calls the method to search:
var wait = setTimeout(search, 800, search_string, $user_list );
$(this).data('timer', wait);
Search Method:
function search( search_string, $user_list ) {
$user_list.find("li").each(function() {
var $this = $(this);
var regex = new RegExp(search_string);
if ( $this.text().match(regex) ||
$this.data('email').match(regex) ) {
console.log("Match Found!!!");
}
});
}
Thanks for you time.
Upvotes: 0
Views: 1070
Reputation: 402
I have an another option for you. you can use jquery autocomplete to get this done. But may be there is a chance that you have to change the html from list elements to something else.Just go through the below example and that might help. Never mind if this is not what you desired.
https://jqueryui.com/autocomplete/#multiple
Upvotes: 0
Reputation: 66488
Using jQuery:
$('ul li').each(function() {
var $this = $(this);
var regex = new RegExp(searchTerm);
var email = $this.data('email')
if ((email && email.match(regex)) ||
$this.text().match(regex)) {
// found li with search term
}
});
Upvotes: 1