Javascript HTML localstorage [closed] - javascript

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
I use localstorage to save items (songs) as favorites. But I would also like to be able to remove the items from the array, so not the key but the value of the key.
for example I have the key Songs and values of one , two, three. I would like to be able to remove two from Songs but one and three should remain.
I cant seem to figure out how to do so because all I can find is how to remove the key and not the value of the key.

Since you don't have any source code on display I will give you quick example of how to remove single values from the clients Local Storage. You can expand on this to remove multiple values. Wouldn't want to remove all the fun
I have commented out the Localstoage and created a Songs array so this will work in the snippet.
Remove /* and */ to uncomment that section and change getItem('Songs') to fit your current source code.
You will also want to remove var Songs[]; Snippet Use only
/*--Local Storage Use
// Get Songs from Local Storage
var Storage = localStorage.getItem('Songs');
//Split Songs into an Array
var Songs=Storage.split(',');
*/
// Snippet Use -- Example Values of the Songs Result
var Songs = ['Song One', 'Song Two', 'Song Three','Song Four'];
//------ Remove Single Value
var Remove = Songs.indexOf('Song Two');
alert('Old Songs List:\n'+Songs);
if (Remove > -1) {
Songs.splice(Remove, 1);
}
alert('New Songs List:\n'+Songs);
//--Update LocalStorage
//localStorage.setItem('Songs',Songs);
If you have any questions about the above example please leave a comment below and I will get back to you as soon as possible.
I hope this helps. Happy coding!

Assuming your Object is structured like this;
"Songs": ["Song One", "Song Two", "Song Three"]
I don't have the code for you, but the process I would go through is;
Read localStorage item (localStorage.getItem('Songs'))
If you know the index of the item, you can then remove it. See this post for details
Re-save the Object to localStorage (localStorage.setItem('Songs', SongsObj)).

You need to get value of localStorage (Songs for example). Save value into variable, then change value (delete/remove some list items), then uses same key (Songs) set previous localStorage key with new value.
localStorage.setItem('Songs', [1,2,3,4,5]);
var songs = localStorage.getItem('Songs');
// ... some operations with list...
songs = [1,3,4];
localStorage.setItem('Songs', songs);

Related

How to remove ıtem on localStorage? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
I want to removeItem on localstorage but ı dont use localstorage.removeItem().Because ı want to delete a index in array(Sepet=array)
How can ı do it ?
thx
var array = [
{
'id': 1,
'name':'test1'
},
{
'id': 2,
'name':'test2'
},
{
'id': 3,
'name':'test3'
}
];
console.log(array);
localStorage.setItem('test', JSON.stringify(array));
var selected = 1;
var getArray = JSON.parse(localStorage.getItem('test'))
getArray.splice(selected,1);
localStorage.setItem('test', JSON.stringify(getArray));
console.log(getArray);
To get object from localStorage you need the Helper: localStorage.getItem('objectName');. You will get a string and not a object. To transform this string to a Object you need the function JSON.parse(string). And on this point you can work with the object. If you will delete item by index then remove it with object[index]and if you will remove item by value key like id: 2 then use JS Object function function like spliceto remove this item.
After that you have to stringify the object again to a string with JSON.stringify(object). This string you can store in the lcoalStorage withe the methode: localStorage.set(string)
That is the entire workflow.
localStorage is meant to store String values, so if you want to remove an item at a particular index, bear in mind that you need to convert the stringyfied array into plain JS array, then remove the item with array.slice(), and save the updated array back to localStorage.
You can checkh the Array.slice() documentation

How do I make it show up how many questions the user gets right? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
I am trying to make a simple Algebra quiz in HTML and JavaScript, but can't figure out how to make it show up how many answers you got correct. I made it to where the it would turn the correct answer variables into booleans, true is correct and false is incorrect. Then I made if and else statements to see how many answers were correct but the alert (which will be changed) is just displaying zero no matter what. Here is a link to my code.
https://jsbin.com/yivapi/edit?,js
Trenner, I'm not going to be able to answer your question properly without untangling your code, so what I thought I'd do is show you a different (and hopefully easier) way to approach the problem. I hope that's okay.
HTML
Here are the inputs for the questions as I imagine you've set them out. I've only used three here for simplicity. There's a submit button which I'll get to in a moment.
<input id="q1" />
<input id="q2" />
<input id="q3" />
<button id="submit">Submit</button>
JavaScript
First we grab our submit button and assign a function getAnswers to its click event.
var submit = document.getElementById('submit');
submit.onclick = getAnswers;
This is a shortcut function to grab the input values so you don't need to keep writing document.getElementById(id).value later.
function getValue(id) {
return document.getElementById(id).value;
}
OK. So now, instead of having a load of if...else statements we're going to use an object to store all of our information. If you've used other languages they might call something like this a hash map. Basically it's a store of information that has key/value pairs and it's great for storing connected information together. In this case each question is a key which has another object as its value, and that object's keys are value and answer, and it's values are the value of the input element and the actual answer.
function getAnswers() {
// create the object
var quiz = {};
// for each question assign set up a new key (question1)
// and get the input value using our shortcut function.
// We set the actual answer here too.
quiz.question1 = { value: getValue('q1'), answer: '2√19' }
quiz.question2 = { value: getValue('q2'), answer: '√87' }
quiz.question3 = { value: getValue('q3'), answer: '8x√2' }
// Once we've loaded the questions, we can check the answers
// We pass in our quiz object as an argument
checkAnswers(quiz);
}
Here we use a loop to iterate over our quiz object. A simple loop of 7 lines instead of all those horrible if...else statements.
function checkAnswers(quiz) {
// set up out correctAnswers variable
var correctAnswers = 0;
// loop over the quiz object and...
for (var q in quiz) {
// ...for each question we test the input value we've stored
// against the answer also held in that object
// If they match increase the correctAnswers variable
if (quiz[q].value === quiz[q].answer) {
correctAnswers++;
}
}
// finally alert the correctAnswers
alert("You got " + correctAnswers + " out of 15 questions right!");
}
This DEMO will show you the working code. Just add 2√19 into the first input box and press submit and you will get an alert of 1 correct answer(s).
Sorry for not directly answering your question, but I hope you find this code interesting and useful. Good luck with your JavaScript coding.

Displaying each item in a JS Array separately [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
I am trying to get Javascript Array to display each group name and group ID on its own line instead of sending the whole array to the next script. Essentially what would be desired is that the group ID and Group Name gets pushed "foreach" to the next script that will use those ids to generate a tab. I have the tab generation done and the data import done, the only thing I cant figure out is how to get the array to display each item separately.
Here is my current code:
$.getJSON("inc/load.php", function(data){
for (var i = 0, len = data.length; i < len; i++) {
var Names = data.group_name[i];
var GroupID = data.group_id[i];
console.log(Names + " " + GroupID)
}
I have searched on here and google and have not found a solution.
EDIT
The data does load information correctly, when you use
console.log(data[i]); it returns this style information in the console log:
Object {group_id: "556336557801913", group_name: "How to Start a Startup"}
Object {group_id: "1448816275428542", group_name: "ARK: Survival Evolved"}
Object {group_id: "286255764917755", group_name: "VIP BUYER ADVANTAGE MEMBER"}
What I would like the end result to be is to take the Group_Id and the Group_name put each into its own variable and then pass those variables to another function. And then repeat for the next item in the array.
Im sorry I am still new to Stackoverflow and learning how to best construct my questions.
Edit:
Rather than using for-in as Paul Rob rightly pointed out, you might just correct the following in your code for a start and that might sort you out.
var Names = data[i].group_name;
var GroupID = data[i].group_id;
End Edit
I think what you want is:
for (var i in data) {
var Names = data[i].group_name;
var GroupID = data[i].group_id;
console.log(Names + " " + GroupID);
}
Don't ask me why i is the index rather than the item, one of those nuances of javascript you just grow to live with and love :)

Easier multiple value changes with jQuery [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I am really in need of this one, because I cann't manually type loads of options for admin panel. Hence I need a quick way to fetch each input/select and add value as I want.
Here's looong sample for one option field:
$("select[name=big_proceed]").val("true");
$("select[name=proceed_action]").val("");
$("input[name=choice_premium]").val("Premium <span>Code</span>");
$("input[name=big_proceed_pts]").val("");
$("#settings_proceed input, #settings_proceed select").each(function () {
databaseData($(this));
});
I thought something like this may work but apparently I was wrong. Here's sample:
$("#settings_proceed :input").each(function () {
$(this)
.eq(0).val("true")
.eq(1).val("")
.eq(2).val("Premium <span>Code</span>")
.eq(3).val("");
databaseData($(this));
});
Any suggestions for me ?
From the jQuery documentation:
.eq(index): Reduce the set of matched elements to the one at the specified index.
Hence your second example doesn't work as intended because $(this) only matches one element (that's the intention behind the .each()). You could rewrite the code like so:
var values = ["true", "", "Premium <span>Code</span>", ""];
$("#settings_proceed :input").each(function(i){
$(this).val(values[i]);
databaseData($(this));
});
However, this approach makes the code hard to read and error-prone because it assumes a fixed order of the HTML elements (what if you change the order of the input fields but forget to adjust the JS accordingly?). So you really should "manually" add IDs to your input elements and select them by their ID and not their index.
As #David Thomas pointed out, some sample HTML would be quite helpful here, but without knowing any further details of what you're trying to do I'd suggest the following:
var values = {
big_proceed: "true",
proceed_action: "",
choice_premium: "Premium <span>Code</span>",
big_proceed_pts: ""
};
$.each(values, function(key, value){
$("#settings_proceed").find("[name='"+key+"']").val(value);
databaseData($(this));
});
That way you can neatly define all the values in one object and let jQuery safely do the rest.

save array values on reload and retrieve it back [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I am pushing some random values into an array every minute.
On reloading I want to retrieve back this pushed content and keep pushing some random data every minute?
I am using local storage.
MyCODE--:
localStorage.setItem("test",Myarray.push(JSON.stringify(data)));
var test2 = localStorage.getItem("test");
test = JSON.parse(test2); //var test is now re-loaded!
console.log(test);
This is not working.
Push the data to the array, then store it in the localStorage as JSON:
// Set
Myarray.push(data);
localStorage.setItem("test", JSON.stringify(Myarray));
Parse the JSON when you get the data back out (put this at the top of your script, or in your onload method):
// Get
if (localStorage.getItem("test")) {
Myarray = JSON.parse(localStorage.getItem("test"));
} else {
// No data, start with an empty array
Myarray = [];
}
console.log(Myarray);
Local Storage works with strings only. Also, push returns the new length of the array, so the code you posted wont work as intended. Try this:
Myarray.push(data);
localStorage.setItem("test", JSON.stringify(Myarray));
The problem is you're storing the return value from .push() to local storage (which is the length of the array), instead of the actual data.
You should push to the array as required, then stringify the array and store.
var Myarray = [];
Myarray.push(....);
localStorage.setItem("test", JSON.stringify(Myarray);

Categories

Resources