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();
}
Related
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);
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 have a working script that upon form submit, specific rows move from one sheet to another. One of the fields I'm pushing is a url.
On the second sheet, the link is listed and it is hyperlinked, but it's really ugly and I really want to format it so that it shows "Edit" with a hyperlink. I've tried a number of ways, but my knowledge is limited so all I get are errors. I'm hoping someone can point me in the right direction.
Here is my code. I'm very new at this so the script is not at all sophisticated. Any help/suggestions would be appreciated!
function copyAdHoc(){
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sh = SpreadsheetApp.setActiveSheet(ss.getSheetByName("Form Responses 1"));
var data = sh.getRange(2, 1, sh.getLastRow() - 1, sh.getLastColumn()).getValues();
// Grab the Headers from master sheet
var headers = sh.getRange(1,1,1,sh.getLastColumn()).getValues();
var date = headers[0].indexOf('Effective Date');
var name = headers[0].indexOf('Employee Name');
var loc = headers[0].indexOf('Location');
var issue = headers[0].indexOf('Description/Question/Issue');
var add = headers[0].indexOf('Additional Information');
var change = headers[0].indexOf('Is this a Qualifying Life Event?');
var url = headers[0].indexOf('Form URL');
var category = headers[0].indexOf('Primary Category');
var status = headers[0].indexOf('Current Status');
var users = headers[0].indexOf('Users');
// Grab only the relevant columns
for(n = 0; n < data.length; ++n ) { // iterate in the array, row by row
if (data[n][change] !== "Yes" & data[n][category] !== "Employee Relations" & data[n][date] !== "") { // if condition is true copy the whole row to target
var arr = [];
arr.push(data[n][url]);
arr.push(data[n][users]);
arr.push(data[n][date]);
arr.push(data[n][loc]);
arr.push(data[n][name]);
arr.push(data[n][category]);
arr.push(data[n][issue] + ". " + data[n][add]);
arr.push(data[n][status]);
var sh2 = SpreadsheetApp.setActiveSheet(ss.getSheetByName("Ad Hoc")); //second sheet of your spreadsheet
sh2.getRange(sh2.getLastRow()+1,2,1,arr.length).setValues([arr]); // paste the selected values in the 2cond sheet in one batch write
}
}
}
It's a bit messy but the only way I know to achieve what you're trying to do would be to insert a column to the left of the hyperlink with the word Edit right justified and then remove the borders between the two.
From your description I am assuming you want the word "Edit" to be Hyperlinked. To do so, try this:
function getHyperlink(url)
{
return "=HYPERLINK(\""+url+"\","+"\"Edit\""+")";
}
function mainFunct()
{
//Do necessary steps
var tarLink = "https://www.google.com";
var tarRng = tarSheet.getRange(rowNum, colNum).setValue(getHyperlink(tarLink));
//perform other steps
}
EDIT:
Forgot to mention, since you're pushing your values to the array... you can do it in a similar way by either just storing the hyperlink in a variable or directly pushing it to the array like all the other values. Or if you're dealing with a hyperlink that has a static and dynamic part, For example: https://stackoverflow.com/questions/post_id, where post_id keeps changing but most of the URL is static, you can easily handle it by just passing the post_id to the getHyperlink function and getting the required Hyperlink in return. Hope this helps.
i'm new to javascript and jquery and was wondering if someone could let me in on why this isn't working correctly.
i have a drop-down box that a user selects a value from, then "Processes." When processed the value of the drop-down as well as a textbox is stored in an array. I want the user to be able to then basically store the same drop-down selection and textbox data in the array again but now in a new value pair.
First store would be
TestArray[0][0] = "Textbox Value"
If "Processed" again, it would be
TestArray[1][0] = "Textbox Value"
that way I can parse through later and figure how many times the user "Processed" the drop-down selection;
var oneClickReport = $("#reportName").val();
if(oneClickReport == "Sample Report One"){
var arrayOneCount = reportOneArray.length;
var totalHouseholds = 0;
$("#reportChecks span:visible").each(function(){
if($(this).find(':checkbox').prop('checked')){
var HHName = $(this).text();
reportOneArray.push(HHName);
arrayTest[arrayOneCount][totalHouseholds] = HHName;
}
totalHouseholds += 1;
});
for(i = 0; i < arrayOneCount; i+=1){
alert(arrayTest[0][i]);
}
}
But when trying to "Process" for the second time, I receive the error of;
SCRIPT5007: Unable to set property '0' of undefined or null reference
on line;
arrayTest[arrayOneCount][totalHouseholds] = HHName;
You need to initialize your array. I'm not sure what exactly you want to do but you need an array like this
var arrayTest = []
And you will need to initialize subsequent value like
arrayTest[1] = []
Then you can access your array
arrayTest[1][0] = []
I made an example for you
var oneClickReport = $("#reportName").val();
var arrayTest = [] # You may need to put this elsewhere
if(oneClickReport == "Sample Report One"){
var arrayOneCount = reportOneArray.length;
var totalHouseholds = 0;
$("#reportChecks span:visible").each(function(){
if($(this).find(':checkbox').prop('checked')){
var HHName = $(this).text();
reportOneArray.push(HHName);
if(!arrayTest[arrayOneCount]){ arrayTest[arrayOneCount] = []; }
arrayTest[arrayOneCount][totalHouseholds] = HHName;
}
totalHouseholds += 1;
});
for(i = 0; i < arrayOneCount; i+=1){
alert(arrayTest[0][i]);
}
}
your problem with var arrayOneCount = reportOneArray.length; and you're not changing this value
So we had a piece of code that set a few elements to display the count of all items in various lists.
Now a requirement has been added that only items of a certain content type can be counted. However, Including a caml query as seen below (The old code has been commented out) has made it far to slow for actual use. (obviously, its fetching thousands of items just to get a count).
Is there a way to count all items of a contenttype in a sharepoint list using javascript that doesn't request all items of every list?
function setCounter() {
context = new SP.ClientContext.get_current();
web = this.context.get_web();
this.lists = web.get_lists();
context.load(this.lists);
context.executeQueryAsync(
Function.createDelegate(this, function () {
var listsEnumerator = this.lists.getEnumerator();
while (listsEnumerator.moveNext()) {
var currentItem = listsEnumerator.get_current();
for (var i = 0; i < leng; i++) {
if (leng == 1) ele = listItemCount;
else ele = listItemCount[i];
if (decoded == currentItem.get_title()) {
ele.parentNode.setAttribute("class", "overview_discussions");
// var counter = currentItem.getItems();
// ele.innerText = currentItem.get_itemCount();
var camlQuery = new SP.CamlQuery();
camlQuery.set_viewXml("<Where><BeginsWith><FieldRef Name='ContentTypeName'/><Value Type='Text'>Discussion</Value></BeginsWith></Where>");
var counter = currentItem.getItems(camlQuery);
context.load(counter);
context.executeQueryAsync(function () { ele.innerText = counter.get_count(); }, executeOnFailure);
break;
}
}
}
}),
Function.createDelegate(this, executeOnFailure));
}
Nope, but what you can do is minimize the data pulling by setting viewfields. Now is like you are doing a select * when you only need select id
var caml = "<View><ViewFields><FieldRef Name='Id'/></ViewFields></View><Query>your query here</Query>";
After executing the query you just need to cal get_count() as you already do
If you are familiar with jQuery, I suggest you taking a look a this library, is very easy to use and helps you improve your work with object client model. http://spservices.codeplex.com/