Reputation: 209
I have UL list with many items and some input. My script listens to key up on input and show or hide field that match input string.
Here is my code:
$(function(){
$('#srvSearchField').keyup(function(){
var value = $(this).val();
$('.srvClientBlock').each(function(){
var currentFieldValue = $(this).children('.srvClientName').html();
var exp = new RegExp(value);
if (currentFieldValue.match(exp)) {
$(this).show();
} else {
$(this).hide();
}
});
});
});
How can i improve performance? Or i should send request on my server to find matched values?
UPD: I decided use ajax to filter clients.
var url = "<?php echo $searchClientUrl;?>";
$(function(){
$('#srvSearchField').keyup(function(){
var request = $(this).val();
var callback = function(response) {
$('.srvClientBlock').hide();
var data = JSON.parse(response);
for (var i = 0; i < data.length; i++) {
$('#srvClient-' + data[i]).show();
}
};
$.post(url, {"request" : request}, callback);
});
});
Thanks everyone for answers.
Upvotes: 0
Views: 274
Reputation: 664297
Some points:
test
method of the regex instead of match
.Of course, caching only applies if your list contents do not change dynamically (or at least you'd need to rebuild the cache every time).
Sending requests to the server for each search makes only sense under certain circumstances:
but they require enough bandwidth for many requests and a relatively small latency. You can target those problems with special optimizations, though.
// simple improvements, no caching:
$(function(){
$('#srvSearchField').keyup(function(){
var exp = new RegExp( $(this).val() );
$('.srvClientBlock').each(function(){
var $this = $(this);
var currentFieldValue = $this.children('.srvClientName').text();
$this[ exp.test(currentFieldValue) ? "show" : "hide" ]();
});
});
});
Upvotes: 5
Reputation: 2625
If you can avoid ajax requests, do so. You might need to use them though if you are having client-side problems, the browser can handle only so much data.
If you need to work with ajax requests or a lot of data, set up your keydown event to start a 100-300 ms timeout that is reset and restarted on every subsequent keydown, which in turn calls your search function. That way your search will run only when the user is idle for 200ms (not much, but enough to cut down number of search calls by a lot).
Upvotes: 1