Reputation: 21
I know it's probably silly question but I am newbie and can't handle this.
Here is what I have:
<div class="form-group">
<label for="category">Choose category:</label>
<select class="form-control" id="category">
<option>food</option>
<option>drinks</option>
<option>bills</option>
<option>others</option>
</select>
<textarea type="text" id="price" class="input-inline"></textarea>
</div>
<textarea type="text" id="name" class="input-inline"></textarea>
<div id="DisplayItem"></div>
<a href="#" data-role="button" onclick="SaveItem()" style="width:120px;margin:auto">Save it</a>
<a href="#" data-role="button" onclick="DisplayItem()" style="width:150px;margin:auto">Display it</a>
</form>
and script:
function SaveItem() {
localStorage.setItem("category", jQuery("#category").val());
}
function DisplayItem() {
jQuery('#DisplayItem').text(localStorage.getItem("category"));
}
With this code I will get only the category but I would like to get values from all fields. For example I would like to have result like: Your category is 'C', name is 'N' and price 'P'. Where C, N and P stands for values from formular. How can I achieve it with one function?
Thank you
Upvotes: 1
Views: 240
Reputation: 2727
Local Storage can store JavaScript objects, so say you have two categories.
You could build an object like:
localStorage.setItem('categories', {
category1: $("#category").val(), category2: $("#category-two").val()
});
Notice I swapped out jQuery
for the dollar notation $
since it's just an alias to the jQuery object, it does exactly the same but it's shorthand.
You could store an array
var categories = [];
categories.push($('#category-one').val());
categories.push($('#category-two').val());
localStorage.setItem('categories', categories);
Not sure exactly what you're trying to do but you can store many items under one key within the Local Storage API by storing JavaScript objects.
Upvotes: 1
Reputation: 4521
Best option is to manage all related data as an object.
function SaveItem() {
var item = {
category: jQuery("#category").val(),
name: jQuery("#name").val(),
price: jQuery("#price").val()
};
localStorage.setItem("item", JSON.stringify(item)); //JSON.stringify() transforma el objeto en un string en formato JSON para poder guardarlo
}
function DisplayItem() {
var item = JSON.parse(localStorage.getItem("item")); //JSON.parse() transforma un string en formato JSON un objeto
var output = "Category: " + item.category + " - Price: " + item.price + " - Name: " + item.name;
jQuery('#DisplayItem').text(output);
}
Upvotes: 1