search history with localStorage variable in HTML - javascript

I'm creating an jQuery mobile app with PhoneGap and I want to list old search results (entered by a form and stored in localStorage).
There are two different problems to solve:
1) I would store a result in a localStorage array and if the user is searching a second time, the result should be added to the array after the old result like: city[0] = "New York", city[1] = "Paris" ... how can I save and read a string in an array, like:
localStorage.setItem('city[i]', $('#city').val());
or
localStorage.getItem('city[i]');
2) Now I want to show the search history. I've tried this, but:
I don't know how to display the localStorage array or variable in a html list and ...
if no variable in localStorage, the website doesn't load.
<div id="lastResults"></div>
<script>
var history = "";
if (localStorage.getItem("history") !== "") {
var history = localStorage.getItem("history");
}
if ( history !== "") {
$("#lastResults").html(
"<b>Last Results:</b>" +
"<ul data-role=\"listview\" data-inset=\"true\" >" +
"<li> " + document.write(history) + " </li>" +
"</ul>"
);
}
</script>

LocalStorage stores key value pairs where both the key and the value are strings. One way to get around this is to use a JSON object to store your data and use JSON.stringify and JSON.parse to change the data from object to string and back.
EXAMPLE:
var historyObj = { city: [] };
function onLoad() {
if(localStorage.getItem('history')) {
historyObj = JSON.parse(localStorage.getItem('history'));
}
}
function addHistory(dataToSave) {
historyObj.city.push(dataToSave);
localStorage.setItem('history',JSON.stringify(historyObj));
}

<div id="lastResults"></div>
<script type="text/javascript">
//To Check and show previous results in **lastResults** div
if (localStorage.getItem("history") != null)
{
var historyTmp = localStorage.getItem("history");
var oldhistoryarray = historyTmp.split('|');
$('#lastResults').empty();
for(var i =0; i<oldhistoryarray.length; i++)
{
$('#lastResults').append('<p>'+oldhistoryarray[i]+'</p>');
}
}
//Storing New result in previous History localstorage
if (localStorage.getItem("history") != null)
{
var historyTmp = localStorage.getItem("history");
historyTmp += '|Paris|Pakistan|China|US';
localStorage.setItem("history",historyTmp);
}
else
{
var historyTmp = 'Paris|Pakistan|China|US';
localStorage.setItem("history",historyTmp);
}
</script>
Note I have used jquery for code shortening.

Related

Dynamically append Javascript variable to URL

Im attempting to produce a dynamic url containing multiple javascript variables but i only want to include them if they contain information.
These variables are essentially filters which will be used to Select from a MYSQL databse so they take form of "column=value".
The url i am trying to produce will need to be in the format of
page.php?column1=value1&column2=value2.... etc.
i am struggling to work out how to include only the variables that contain info and then how to insert the required "&" between each variable.
The current code is below and currently contains just the two variabls but the aim is to have as many as 5.
var jsedibility = "";
function chosenEdibility(choice){
jsedibility = choice;
}
var jsfrequency = "";
function chosenFrequency(choice2){
jsfrequency = choice2;
}
function setFilters(){
window.location='search.php?' + jsedibility+"&"+jsfrequency;
}
i am then using "onClick=setFilters()" assigned to a button to load the relevant page.
How can i set this up so that the URL is produced dynamically, only containing the variables that have data in them and also to add the required "&" between each variable.
Massively appreciate any help :)
I would make an array of the variables then use join().
var filters = [];
Use an if statement to check that they are not empty strings.
if (jsedibility != ""){ filters.push(jsedibility) }
var filtersString = filters.join('&');
Then in your setFilters(),
window.location.assign('./' + filtersString)
This works with any number of variables.
// mockup data object
const obj = {
jsedibility: '',
jsfrequency: '',
jsvar1: '',
jsvar2: '',
jsvar3: ''
}
// setting object values
function setObjVal(obj) {
obj.jsedibility = 'choice1'
obj.jsfrequency = 'choice2'
}
// creating the filter string
function setFilters(obj) {
return Object.values(obj).filter(val => val !== '').join('&')
}
document.getElementById('setFilters').addEventListener('click', function(e) {
setObjVal(obj)
console.log(setFilters(obj))
})
<button id="setFilters">Filters</button>
Or another with an array:
// mockup data
const choice = 'ch1'
const choice2 = 'ch2'
const array = []
var jsedibility = "";
function chosenEdibility(choice) {
jsedibility = choice;
}
var jsfrequency = "";
function chosenFrequency(choice2) {
jsfrequency = choice2;
}
// showing that it can be filtered out
var noValue = "";
function chosenNoValue(choice3) {
noValue = choice3;
}
chosenEdibility(choice)
chosenNoValue('') // empty value
chosenFrequency(choice2)
document.getElementById('setFilters').addEventListener('click', function(e) {
array.push(jsedibility)
array.push(noValue)
array.push(jsfrequency)
// string filtered for not empty values
const filterString = array.filter(el => el !== '').join('&')
console.log(filterString)
})
<button id="setFilters">Filters</button>

Store same local storage item multiple times

I can enter text and search for data, and then store that data, in this case a name.
localStorage.setItem("name", currentWeather.name);
Using the for loop (while on the same page), I can do multiple searches and the name data for each search is displayed on the page.
for (var i = 0; i < localStorage.length; i++){
$("#record").append(localStorage.getItem(localStorage.key(i)));
}
I now want to be able to store each name, so when I return to that page it still shows them all. Currently local storage is only capable of storing the latest name. I am guessing I need to create an array that I can store each search term into but not sure how to go about it. I have seen some suggest it can be done this way and other people have simply said it is not possible.
$(document).ready(function(){
$('#submitLocation').click(function(){
//get value from input field
var city = $("#city").val();
//check not empty
if (city !== ''){
$.ajax({
url: "http://api.openweathermap.org/data/2.5/weather?q=" + city + "&units=metric" + "&APPID",
type: "GET",
dataType: "jsonp",
success: function(weatherData){
var currentWeather = showCurrent(weatherData);
}
});
}else{
$('#error').html('Field cannot be empty');
}
});
});
function showCurrent(currentWeather) {
console.log(currentWeather);
console.log(currentWeather.name);
if (typeof(Storage) !== "undefined") {
// Store
//saves name in local storage (for histoy list)
localStorage.setItem("name", currentWeather.name);
//saves name in session storage for current use
sessionStorage.setItem("name", currentWeather.name);
// Retrieve
// Retrieves name from session storage
document.getElementById("name").innerHTML = sessionStorage.getItem("name");
// Retrieves name from local storage for history list
document.getElementById("name").innerHTML = localStorage.getItem("name");
// Outputs all locations searched
for (var i = 0; i < localStorage.length; i++){
$("#record").append(localStorage.getItem(localStorage.key(i)));
}
}
else {
document.getElementById("error").innerHTML = "Sorry, your browser does not support Web Storage...";
}
localStorage only stores strings, so to store an array or object you use JSON.stringify.
var names = [ 'Philbo', 'Nipwip', 'Henk' ];
localStorage.setItem( 'names', JSON.stringify( names ) );
And you retrieve it with JSON.parse.
var names = JSON.parse( localStorage.getItem('names') );
Let's get silly and append a new name in a one-liner:
localStorage.setItem( 'names',
JSON.stringify(
JSON.parse(
localStorage.getItem( 'names' ) || '[]'
).concat([ 'Billiam' ])
)
)
For your problem:
var weather = [];
function showCurrent(currentWeather) {
weather.push( currentWeather.name );
if (typeof(Storage) !== "undefined") {
localStorage.setItem("weather", JSON.stringify( weather ) );
...
document.getElementById("name").innerHTML = JSON.parse( localStorage.getItem("weather") );
At first glance, it seems as though you are setting the same key over and over, so you'd only ever have one key-value pair in your localStorage ("name"). Even if you stored the currentWeather.name value in an array, you'd still end up reassigning the same "name" key over and over.
Instead, you could make the assigned key dynamic, such as
localStorage.setItem(currentWeather.id, currentWeather.name);
Or something to that effect. I don't know what properties your currentWeather object will have. You could even simply assign the name value to both arguments of setItem.

How do I extract JSON string using a JavaScript variable?

I am currently trying to retrieve the corresponding dial_code by using the name which I am obtaining as a variable.
The application uses a map of the world. When the user hovers over a particular country, that country is obtained using 'getRegionName'. This is then used to alter the variable name. How can I use the variable name to retrieve the dial_code that it relates to?
JSON
var dialCodes = [
{"name":"China","dial_code":"+86","code":"CN"},
{"name":"Afghanistan","dial_code":"+93","code":"AF"}
];
The following code runs on mouse hover of a country
var countryName = map.getRegionName(code);
label.html(name + ' (' + code.toString() + ')<br>' + dialCodes[0][countryName].dial_code);
This code doesn't work correctly. The dialCodes[0][countryName].dial_code is the part that is causing the error, but I'm not sure how to correctly refer to the corresponding key/value pair
If you have to support old browsers:
Loop over the entries in the array and compare to the given name:
var dialCode;
for(var i = 0; i < dialCodes.length; i++) {
if(dialCodes[i].name === countryName) {
dialCode = dialCodes[i].dial_code;
break;
}
}
label.html(countryName + ' (' + dialCode + ')');
If you browser support Array.prototype.filter:
dialCodes.filter(function(e) { return e.name === 'China' })[0].dial_code
If you have control over it, I recommend making your object more like a dictionary, for example if you are always looking up by the code (CN or AF) you could avoid looping if you did this:
var dialCodes = {
CN: { "name":"China","dial_code":"+86","code":"CN" },
AF: {"name":"Afghanistan","dial_code":"+93","code":"AF"}
};
var code = dialCodes.CN.dial_code;
Or
var myCode = 'CN'; // for example
var code = dialCodes[myCode].dial_code;
Since it's an array you can use filter to extract the data you need.
function getData(type, val) {
return dialCodes.filter(function (el) {
return el[type] === val;
})[0];
}
getData('code', 'CN').dial_code; // +86

how to remove concatenated data in localStorage

I'm using localStorage to store some data and all the data are concatenated separated by \n. I want to remove specific data in localStorage and i'm using listbox to display all the data.
example {"rowdata":"data1\ndata2\ndata3"} // the three data are stored in localStorage, the key of rowdata in the localStorage is storedata and the rowdata is the value of storedata that have three data concatenated.
is there an easy way to remove the selected data, example i want to remove data3. i'm using google chrome browser..
code for display:
function populate(){
for(i=0; i<rowdata.length; i++){
var select = document.getElementById("test"); // id of the listbox
var splitRow = rowdata.split("\n");
var row = splitRow[i];
if(row != undefined)
select.options[select.options.length] = new Option(row);
}
}
code for remove:
function removeSelectedItem(){
var htmlSelect=document.getElementById('test'); // id of the listbox
if(htmlSelect.options.length == 0)
{
alert('You have already removed all list items');
return false;
{
var optionToRemove = htmlSelect.options.selectedIndex;
htmlSelect.remove(optionToRemove);
if(htmlSelect.options.length > 0)
{
htmlSelect.options[0].selected=true;
{
alert('The selected data has been removed successfully');
return true;
}
Thanks...
Not sure if I clearly understood the question, but if you just need to update state if rowdata variable then try put the code below before removing an option from select in RemoveSelectedItem (man, start function names with lowercase!):
rowdata = ("\n" + rowdata + "\n").replace("\n" + htmlSelect.options[htmlSelect.options.selectedIndex].innerHTML + "\n", "").trim()

how to check if an item exist in sessionstorage?

I am creating a web page where the user can add an item into a dropbox buy clicking a button. The sessionstorage store the partnum and quantity of the item. The dropbox will display the details (quantity would be 1)of the item selected. How do I update the quantity to 2 if the same item is selected?
$("#btnBuy0").click(function()
{
$("#dropbox").append('<span><img class = "thumb" src="../images/21_metoyou.jpg" />' + teddy[0].desc + ", Price £"
+ teddy[0].price + ", Quantity: " + quantity + "</span><br/>");
if (Modernizr.sessionstorage)
{ // check if the browser supports sessionStorage
myids.push(teddy[0].partnum + quantity); // add the current username to the myids array
sessionStorage["ids"]=JSON.stringify(myids); // convert it to a string and put into sessionStorage
}
else
{
// use cookies instead of sessionStorage
}
for (var item =0; item<sessionStroage.length; item++)
{
var key = sessionStorage.key(teddy[0].partum);
if (teddy[0].partnum == teddy[item].partnum)
{
var q = sesstionStorage.getItem(quantity, quantity++);
}
I would suggest you make use of a differnt data structure for storing the user's basket. Instead of using an Array (myids), you could make use of an Associative Array (by using a JavaScript object) to map the partnum against a quantity, eg:
// Basket is initially empty.
basket = {};
function saveOrder(teddy, quantity) {
var partnum = teddy[0].partnum;
// Create a mapping between the partnum and the quantity
basket[partnum] = quantity;
// Write the basket to sessionStorage.
sessionStorage.basket = JSON.stringify(basket);
}
Using a map would allow you to create helper methods to read and write the basket object from SessionStorage, eg:
function fetchBasketFromSession() {
return JSON.parse(sessionStorage.basket);
}
function writeBasketToSession(basket) {
sessionStorage.basket = JSON.stringify(basket)
}
function getPartNumOf(teddy) {
return teddy[0].partnum;
}
function getQuantityInSessionBasketOf(teddy) {
// Fetch the basket from sessionStorage
var sessionBasket = fetchBasketFromSession(),
partnum = getPartNumOf(teddy);
// Return the quantity mapped to the partnum in the basket, or 0 if nothing
// is mapped.
return sessionBasket[partnum] || 0;
}
// Combining these functions would allow you to update the users basket.
function addToBasket(teddy, quantityToAdd) {
var sessionBasket = fetchBasketFromSession(),
currentQuantity = getQuantityInSessionBasketOf(teddy),
partnum = getPartNumOf(teddy);
// Update the quantity for this partnum and write it back out.
sessionBasket[partnum] = currentQuantity + quantityToAdd;
writeBasketToSession(sessionBasket);
}
Hope that helps :)

Categories