Primary requirement
What I really wants to achieve is that there is a text box with a button where user can input values and then those values will be saved into localStorage via different keys (so that even in page refresh these values can be retrieved) and also inserted values will be displayed under the text box.
What I did to accomplish this:
HTML
<div>
<input type="text" name="userInputs" placeholder="Please insert the value" id="idUserInputs">
<button onclick="insertUserInput()">Add</button>
<p id="hiddenP"></p>
</div>
JavaScript
<script>
var i = 0;
function insertUserInput() {
i++;
//fetch the value
var insertedValue = document.getElementById("idUserInputs").value;
//set the value to show user
document.getElementById("hiddenP").innerHTML = insertedValue;
//set the value to localstorage with different key(via incremental i)
window.localStorage.setItem("savedValues" + i, insertedValue);
}
</script>
To retrieve the data if user refresh the tab just added <body onload=funcrtion() and the function coded as shown below:
<body onload="onloadRetrieveData()">
function onloadRetrieveData() {
//check the length
var length = localStorage.length;
var x;
for (x = 1; x <= length; x++) {
document.getElementById("hiddenP").innerHTML = window.localStorage.getItem('savedValues' + x);
}
This will retrieve the last data that user inserted. Like below
I started this based on this article
The complete guide to using localStorage in JavaScript apps
What I wants right now is when user refresh the tab all saved data in local storage to be retrieve and show to user. Can anyone help me with this? Thanks
Here is one way one way to accomplish this, using the code you already have with a few small adjustments for how you add the final result to the DOM:
var hiddenP = document.getElementById('hiddenP');
var ul = document.createElement('ul');
function onloadRetriveData() {
//check the length
var length = localStorage.length;
var storedValues = [];
console.log(length);
var x;
for (x = 1; x <= length; x++) {
var li = document.createElement('li');
var textContent = document.createTextNode(window.localStorage.getItem('savedValues' + x));
li.appendChild(textContent);
ul.appendChild(li);
}
hiddenP.appendChild(ul);
}
That would show all of the items in local storage in an unordered list, you could of course choose to display them in any format you wish.
Here is a short summary of what's going on, in case anything is unclear.
Code Summary
In this version, we are creating an unordered list:
var ul = document.createElement('ul');
Then, we add each item from local storage to the list as we go through the loop:
for (x = 1; x <= length; x++) {
var li = document.createElement('li');
var textContent = document.createTextNode(window.localStorage.getItem('savedValues' + x));
li.appendChild(textContent);
ul.appendChild(li);
}
Notice that we create a new list element each pass:
var li = document.createElement('li');
Then, we create a textNode with the item from local storage as the value:
var textContent = document.createTextNode(window.localStorage.getItem('savedValues' + x));
Then, we add this text node to the list item and finally add the list item to the unordered list using the appendChild() method:
li.appendChild(textContent);
ul.appendChild(li);
Then, after the loop, we add the whole list to the hiddenP paragraph element, again using the appendChild() method:
hiddenP.appendChild(ul);
Related
I have created a list using a for loop and want to add an event listener to each of them, so that when each item is clicked, it's logged in the console the item number (e.g. if list item 1 is clicked, console log returns the variable currentNumber as 0).
However, with my current code, all I'm getting in the console log is "4". Can someone please help me with this? Thank you.
for (i = 0; i < tipsCatalog.length; i++) {
var newCategory = document.createElement('li');
newCategory.id = "sMonTipHeadline-" + [i];
newCategory.className = "sMonTipHeadline";
newCategory.innerHTML = tipsCatalog[i].tipHeadline;
catalogContainer.appendChild(newCategory);
}
var currentNumber = [];
for (i = 0; i < tipsCatalog.length; i++) {
currentNumber[i] = i;
tipsCatalogList[i].addEventListener('click', function() {console.log(currentNumber[i])});
}
I would try to add the number inside an element's attribute and then take it from there when you need it.
tipsCatalogList[i].addEventListener('click', function() {console.log($(this).attr('yournumber'))});
I have a mobile app where I want users to be able to save locations in their localStorage. I have a blank HTML page called "Saved Locations." When a user navigates to this page, I want hyperlinks to be created dynamically from whatever locations are saved in the device. I'm able to iterate through the keys and list them, but I've had trouble trying to create div elements on the fly. Here's my JavaScript:
myApp.onPageInit('saved_locations', function (page) {
var fragment = document.createDocumentFragment();
var parent = document.getElementById("saved");
// iterate localStorage
for (var i = 0; i < localStorage.length; i++) {
// set iteration key name
var key = localStorage.key(i);
// use key name to retrieve the corresponding value
var value = localStorage.getItem(key);
// console.log the iteration key and value
console.log('Key: ' + key + ', Value: ' + value);
let node = document.createElement("div") ;
let text = document.createTextNode(key); //value is taken from your loop
node.appendChild(text);
fragment.appendChild(node);
}
parent.appendChild(fragment);
});
Assign and Id to the element where you want them to appear. Then
var fragment = document.createDocumentFragment();
var parent = document.getElementById("yourId");
loop goes here {
let node = document.createElement("div") ;
let text = document.createTextNode(value); //value is taken from your loop
node.appendChild(text);
fragment.appendChild(node);
}
parent.appendChild(fragment);
So, i have this code, it works:
var curp = document.getElementById("id_sc_field_curp_id_1");
var getcurp = curp.options[curp.selectedIndex].text;
var rfc = getcurp.substr(0, 10);
document.getElementById("id_sc_field_virtual_rfc_1").value = rfc;
It copy the text inside the field (td - CURP) "id_sc_field_curp_id_1", and trim it to put the result in another field (RFC) "id_sc_field_virtual_rfc_1"
Example img
JSFIDDLE: https://jsfiddle.net/90yzgcqe/1/
I want to adapt the code to work with the other rows, witch have an incremental id...
id_sc_field_curp_id_1,id_sc_field_curp_id_2,id_sc_field_curp_id_3, d_sc_field_virtual_rfc_1, d_sc_field_virtual_rfc_2, d_sc_field_virtual_rfc_3...etc
Im making this function, but... i dont know how to make it work...
function rfc() {
for (var i = 0; i <= 19; i++) {
var curp = document.getElementById("id_sc_field_curp_id_" + i);
var getcurp = curp.options[curp.selectedIndex].text;
var rfc = getcurp.substr(0, 10);
document.getElementById("id_sc_field_virtual_rfc_" + i).value = rfc;
}
}
What is wrong?
Some jQuery gets us there fairly easily, first get the matching dropdowns and then interact with them.
$(function() {
//get the list of dropdowns that start with all but the numeral
var lst = $("[id^='id_sc_field_curp_id_']");
$.each(lst, function(idx, elem) {
//lets store the dropdown for use in the loop
let $field = $(elem);
//for example lets print the selected text
console.log($field.find("option:selected").text());
});
});
There are a couple of options from there, you can use the dropdown to create the rfc's id, or use the jQuery function closest() to get it. Once you have the associated rfc's input it should be trivial to get set the value.
EDITED:1
More specific javascript, and a link to a modified jsFiddle
$(function() {
//get the list of dropdowns that start with all but the numeral
var lst = $("[id^='id_sc_field_curp_id_']");
$.each(lst, function(idx, elem) {
//lets store the dropdown for use in the loop
let $field = $(elem);
//for example lets alert the selected text
alert($field.find("option:selected").text().substr(0,10));
$field.closest("[id^='idVertRow']")
.find("[id^='id_sc_field_virtual_rfc_']")
.val($field.find("option:selected").text().substr(0,10));
});
});
I've been trying this for a while now and could not find anything online...
I have a project, where tablerows get added to a table. Works fine.
Now I want to save the Table in the localStorage, so I can load it again. (overwrite the existing table).
function saveProject(){
//TODO: Implement Save functionality
var projects = [];
projects.push($('#tubes table')[0].innerHTML);
localStorage.setItem('projects', projects);
//console.log(localStorage.getItem('projects'));
The problem is the Array "projects" has (after one save) 2000+ elements. But all I want is the whole table to be saved to the first (or appending later) index.
In the end I want the different Saves to be listed on a Option element:
function loadSaveStates(){
alert('loading saved states...');
var projects = localStorage.getItem('projects');
select = document.getElementById('selectSave'); //my Dropdown
var length = projects.length,
element = null;
console.log(length);
for (var i = 0; i < length; i++) {
element = projects[i];
var opt = document.createElement('option');
opt.value = i;
opt.innerHTML = 'project ' + i;
select.appendChild(opt);
}
}
Can anyone tell me what I am doing wrong?
You can easily do this by jquery, are you interested in this, if yes.. then try following code
For setting the value
$.jStorage.set("projects", $.trim(projects));
For Getting the data
$.jStorage.get("projects");
For deleting the data with key
$.jStorage.deleteKey("projects");
I coose to stay with localStorage, but insted of using an Array I just let the user give every project a name and create a new Item for every Save:
function saveProject(){
//TODO: Implement Save functionality
var pname=prompt("Please enter your project name:","projectname")
var text = $('#mainTable')[0].innerHTML;
//console.log(text);
localStorage.setItem(pname, text);
//console.log(localStorage.key(2));
loadSaveStates();
}
function loadProject(){
var selected = $('#selectSave')[0].selectedIndex
//console.log(selected);
if (localStorage.key(selected) == 'jStorage'){
selected++;
}
var innerHTMLTable = localStorage[localStorage.key(selected)];
//console.log(innerHTMLTable);
$('#mainTable')[0].innerHTML = innerHTMLTable;
updateHandlers();
}
function deleteProject(){
var selected = $('#selectSave')[0].selectedIndex
var pname = $('#selectSave')[0].options[selected].value
$('#selectSave')[0].remove(selected);
localStorage.removeItem(pname);
//console.log(pname);
loadSaveStates();
}
I was trying to get the country name and put it in the temparray, so that I can use the temparray to check the country (line 14). The problem is temparray can only contain one value and upon increasing the array length size by using temparray.length = 4, the heat map won't show up in the page.
The code below is to check duplicate name entry from within the array. If the country name is repeated, it will add the past value and its current value and add it into the data table again as the old row.
var i;
var suq = 0;
var temparray = [""];
var rowcount= 0;
//set the value
for (i = 0; i<count; i++){
var countryname = countryarray[i];
var hostcount = hosthitcount[i];
//document.write("hello");
for (rowcount=0;rowcount<temparray.length;rowcount++){
//check for any repeated country name
if (temparray[rowcount] != countryname){
data.setValue(suq, 0, countryname);
data.setValue(suq, 1, hostcount);
temparray[rowcount] = countryname;
//document.write("win");document.write("<br/>");
suq++;
}else{
//get the hits //rowindex
var pastvalue = data.getValue(rowcount,1);
//add the previous value with current value
var value = parseInt(hostcount)+parseInt(pastvalue);
value+= "";
//document.write(value);
//put it in the table
data.setValue(rowcount,1,value);
// document.write("lose");document.write("<br/>");
}
}
}
I don't really understand what you are trying to do with temparray. It can surely contain more than one element with a temparray.push(countryname). Maybe this JavaScript array reference will help you?