Reputation: 28032
I have a webpage with a large list of records (say 250+ rows of data in a table) and want to be able to just visit the page, immediately start typing, and have it jump me to the first row that matches the text I have typed.
Ideally, if I then continued to type more characters so the first match doesn't match anymore, it could then continue to respond to my input and jump me to the new match.
I've tried with window.find() but haven't had much success... can anyone reccomend a working solution?
I'm essentially looking for the equivalent to hitting 'CTRL-F' on my keyboard... except without the need to hit CTRL-F to make it happen.
Upvotes: 19
Views: 57701
Reputation: 1129
There's this prototype which is NOT recommended (as of 19/07/21) to be used on PROD sites , but if you want to give a try , then it's pretty simple & best part is that it's 1st party .
Just type this on your console in this stack overflow window itself :
window.find("Aniket");
More info can be found here - https://developer.mozilla.org/en-US/docs/Web/API/Window/find
Upvotes: 1
Reputation: 21226
I think the tricky part of this is actually the accepting of user input intelligently. Therefore, I'd say the best thing to do is to pass off your searching to an autocomplete-type plugin. Once the page is ready, you pass the focus to an input text box, and then let the plugin do its magic as you search...
For example, you could use the quicksearch plugin.
Then given a table of data and an input like this:
<input id="searcher" type="text" name="searcher">
You could have a ready function that looks like this:
$('#searcher').quicksearch('table tbody tr', {
'delay': 100,
'bind': 'keyup keydown',
'show': function() {
if ($('#searcher').val() === '') {
return;
}
$(this).addClass('show');
},
'onAfter': function() {
if ($('#searcher').val() === '') {
return;
}
if ($('.show:first').length > 0){
$('html,body').scrollTop($('.show:first').offset().top);
}
},
'hide': function() {
$(this).removeClass('show');
},
'prepareQuery': function(val) {
return new RegExp(val, "i");
},
'testQuery': function(query, txt, _row) {
return query.test(txt);
}
});
$('#searcher').focus();
Try it out here: http://jsfiddle.net/ZLhAd/369/
EDIT: other answer/comment added in to make the input fixed and stop the scollbar jumping around so ridiculously.
Upvotes: 17
Reputation: 21226
OK, here's a different take, using keypress directly:
http://jsfiddle.net/ryleyb/VFVZL/1/
Basically, bind keypress and use that:
$('body').keypress(function(e) {
$('#typed').append(String.fromCharCode(e.which));
if (!findString($('#typed').text())) {
$('#typed').text('');
}
});
findString
is just some vaguely cross browser page string finder. See the fiddle for details.
Upvotes: 9