Reputation: 164
I am trying to cache what has been typed into search area and then use it for another search. check out the below picture to see what I am trying to achieve.
Some of you may wonder why I did not use the form autocomplete attribute. The reason is that there is no removing the cached data. I want to bind it to a button to clear all cached data however the only way to do that as much as I know to disable the autocomplete attribute. please correct me if I am wrong. therefore I decided to use localstorage.
here is the below fiddle to look at it. I am wondering if it is possible to use the source function of autocomplete as I have intended to use.
<form>
<input type="text" id="myInput">
</form>
jQuery('#myInput').autocomplete({
source: localStorage.getItem(key)
});
var list = [];
const form = document.querySelector('form');
const input = document.getElementById('myInput');
form.addEventListener('submit', function(e) {
e.preventDefault();
list.push(input.value);
localStorage.setItem('items', JSON.stringify(list));
input.value = "";
console.log(list);
for (i = 0; i < localStorage.length; i++) {
let key = localStorage.key(i);
console.log("localStorage.getItem", localStorage.getItem(key));
jQuery('#myInput').autocomplete({
source: localStorage.getItem(key)
});
}
});
https://jsfiddle.net/cagatay07/6gqfozpr/92/
Upvotes: 0
Views: 291
Reputation: 30893
Consider the following.
$(function() {
function getList() {
return JSON.parse(localStorage.list) || [];
}
function saveList(arr) {
localStorage.setItem("list", JSON.stringify(arr));
}
function updateList(item) {
var l = getList();
if (l.indexOf(item) < 0) {
l.push(item);
}
saveList(l);
}
$("form").submit(function(e) {
e.preventDefault();
updateList($("#myInput").val());
return true;
});
var list = getList();
$("#myInput").autocomplete({
source: list
});
});
Working Example: https://jsfiddle.net/Twisty/9dq2s80z/26/
Each time the form is submitted, it updates the Local Storage. This is then used in Autocomplete.
Upvotes: 1