Reputation: 1093
I have a simple application with a search textbox and a repeater. When user enters a text in the search textbox, the list is filtered by the entered text. Here's the javascript code which is working fine:
<script type="text/javascript">
$(document).ready(function(){
$('input').keyup(function(){
localStorage.setItem("filterString", this.value);
filter(this);
});
});
function filter(element) {
var value = $(element).val().toLowerCase();
$(".panel").each(function () {
if ($(this).text().toLowerCase().indexOf(value) > -1) {
$(this).show();
} else {
$(this).hide();
}
});
}
</script>
I want to the application to keep the filtered list when user comes back to this page.
The approach I'm trying to make is to store the search string by using the localStorage:
localStorage.setItem("filterString", this.value);"
And then when the window.onload gets called, I retrieve the filterString, render the search textbox, and call the filter function.
Here's the code I've tried:
window.onload = function()
{
if(typeof(Storage) !== "undefined")
{
var filterString = localStorage.getItem("filterString");
txtSearch.value = filterString;
filter(filterString);
}
}
The filter still works fine on keyup
but does not work on onload
.
I've also tried:
$(document).ready(function(){
$('input').keyup(function () {
localStorage.setItem("filterString", this.value);
filter(this);
});
//Added this
filter(localStorage.getItem("filterString"));
});
This is still not working and filter on keyup
stops working if I do this.
Why can't I call the filter
function?
Any advice is appreciated.
Upvotes: 0
Views: 680
Reputation: 4769
Just add following in document.ready function . Remember to call it after your existing function.
$('input').keyup();
like this
$(document).ready(function(){
$('input').keyup(function(){
localStorage.setItem("filterString", this.value);
filter(this);
});
$('input').keyup(); //added here ,after your keyup function
});
Upvotes: 1
Reputation: 11725
The problem is that you're trying to call the filter
function by passing the string as a parameter, and it expects you to pass the element
.
So, you should change your last code to something like:
$(document).ready(function(){
$('input').keyup(function () {
localStorage.setItem("filterString", this.value);
filter(this);
});
// Change the input value to the localStorage value
$('input').val(localStorage.getItem("filterString"));
// And then, send the element to the filter
filter($('input')[0]); ;
});
Upvotes: 1