Hello everybody I am relatively new to coding. I have a local storage project in object oriented javascript for reservation data and to display them in a reservation summary.I am currently blocked, I manage to recover the various values with "getItem", but when I want to display them on my html it displays "object HTMLSpanElement".
the only solution I found is to add ".textcontent" at the end of my variables but it doesn't work.
this is my code
class information{
constructor(){
this.StationName = document.getElementById("StationName");
this.name = document.getElementById("name");
this.firstname = document.getElementById("firstname");
this.adresse = document.getElementById("adresse");
this.PlacesTotal = document.getElementById("PlacesTotal");
this.nbrVeloDispo = document.getElementById("nbrVeloDispo");
};
initstorage(){
var StationName = document.getElementById("StationName").textContent;
var name = document.getElementById("name").value;
var firstname = document.getElementById("firstname").value
var adresse = document.getElementById("adresse").textContent;
var PlacesTotal = document.getElementById("PlacesTotal").textContent;
var nbrVeloDispo = document.getElementById("nbrVeloDispo").textContent;
};
initreservation(){
var StationName = localStorage.getItem("StationName");
var name = localStorage.getItem("name");
var firstname = localStorage.getItem("firstname");
var adresse = localStorage.getItem("adresse");
var PlacesTotal = localStorage.getItem("PlacesTotal");
var nbrVeloDispo = localStorage.getItem("nbrVeloDispo");
};
reserver(){
document.getElementById("signature").style.display = "block";
document.getElementById("panneaureservation").style.display = "none";
};
};
document.getElementById("reservation1").innerHTML = StationName;
const stockage = new information();
document.getElementById("reserve").onclick = function() { stockage.initstorage(); stockage.initreservation(); stockage.reserver(); }
Thank you for taking your time to help me.
When you call localStorage.setItem() you are attempting to store a reference to the DOM element itself instead of the content of that element. Since localStorage only stores strings, the object implicitly gets its .toString() method called on it and a string representation of the object's type and element name is what gets stored.
Here's an example of what's happening (described above):
console.log(document.querySelector("div").toString());
<div>My div element</div>
Once that happens, you can't extract the reference later because all you have is the string name of the object.
You didn't show that code, but that's what needs to be updated. It should store the string value that you will want to get later. Something like this:
localStorage.setItem("StationName", document.getElementById("StationName").textContent);
localStorage.setItem("name", document.getElementById("name").value);
localStorage.setItem("firstname", document.getElementById("firstname").value);
localStorage.setItem("adresse", document.getElementById("adresse").textContent);
localStorage.setItem("PlacesTotal", document.getElementById("PlacesTotal").textContent);
localStorage.setItem("nbrVeloDispo", document.getElementById("nbrVeloDispo").textContent);
Where you set the .textContent of non-form field DOM elements and the .value of form field DOM elements. And, of course, you don't want this code to run against form field data until the form has been completed.
Related
I am new to this. I want to insert variable (not text) into my code:
var events = {};
events[new Date("03/05/2019")] = new Event("Math", "green");
Now when you click text "Math" appears.
I want to insert variable - not directly as a text, but like this:
var subject = Math;
var events = {};
events[new Date("03/05/2019")] = new Event( ?subject? , "green");
to get the same result.
First you need to make Math a string, otherwise you are passing the reference Math as a parameter, and Math is an object provided by JavaScript.
You then just need to use the variable that it is assigned to (in this case subject) and pass that as a parameter to the Event class constructor.
var subject = 'Math';
var events = {};
events[new Date("03/05/2019")] = new Event(subject, "green");
I am learning extendscript for scripting adobe illustrator.It is very difficult for me to write xml related parsing.
My problem statement is given below:- "I have taken three text boxes namely name,city and country."name" is a unique key.when i click ok button the data must be saved in xml if name does not exist else update the previous name with out creating duplicate.All the names in xml file are displayed in list box.The date of particular name could be deleted by remove button.which will remove data in selected item of list box.
The code i tried to do is:-
var myWindow = new Window ("dialog", "Form");
var txt1 = myWindow.add ("edittext");//name unique
var txt2 = myWindow.add ("edittext");//city
var txt3 = myWindow.add ("edittext");//country
var btn=myWindow.add ("button", undefined, "OK");
btn.onClick = function () {
for (i=0;i<numberofnamesinxml;i++)//coding required
{
if(txt1.text!=xmlname[i]) // to verify name not there since it is like primary key
xmlFile.open("a");
xmlFile.write(root.toXMLString());
xmlFile.copy ('C:/data.xml');
xmlFile.close();
//myList refresh
}
}
var myList = myWindow.add ("listbox");
for (i=0;i<numberofnamesinxml;i++)//coding required
{
config='C:/data.xml';
config.open("r");
data= xmlname[i] //here i need to set data to
config.close();
myList.add ("item", data);
}
var btn1=myWindow.add ("button", undefined, "remove");
btn1.onClick = function () {
myList.remove (myList1.selection[i]);
//xml data having this list name must be removed
}
myWindow.show ();
Please kindly help me.
This should not be considered a full answer. I still post it because it might help finding one.
This is what I tried to write as an answer. The read/write part works but the checking of an element exists fails.
if the child is not an exact match, xml.contains(xml) will not return true.
var path = '~/Desktop/test.xml';
var xmlfile = File(path);
if (!xmlfile.exists) {
$.writeln('xml file does not exist. Creating new one');
xmlfile = new File(path);
xmlfile.open('w');
xmlfile.write('<Root></Root>');
xmlfile.close();
}
xmlfile.open('r');
xmlcontent = xmlfile.read();
xmlfile.close();
//$.writeln(xmlcontent);
var xml = new XML(xmlcontent);
// here the problems start
// the check is only working for known elements
var child = new XML('<name data="bob"></name>');
if (xml.contains(child)) {
child.#data = 'jim';
$.writeln('A child called "name" exists. Update');
xml.replace('name', child);
} else {
$.writeln('no child called "name" exists. Append');
child.#data = 'bob';
xml.appendChild(child);
}
xmlfile.open('w');
xmlfile.write(xml.toXMLString());
xmlfile.close();
My real answer is:
Use JSON instead.
I am using the SharePoint JavaScript Object Model within an Angular controller to retrieve data from the Taxonomy (term store). By using $scope.apply, I am able to bind the array to scope and use the values in a dropdown since SharePoint's JavaScript Object Model is not a normal Angular function understood by scope. This works as intended.
Now I need to set the value of the field to the current value stored in the database. This works with the following for dropdown/choice based fields where I retrieve the index of the item via a search of the array. Example:
var currentCategoryIndex = $scope.categoryValues.map(function (e) { return e.value; }).indexOf(currentCategoryValue);
$scope.vm.selectedCategory = $scope.categoryValues[currentCategoryIndex];
However, I can't access my array within the controller to check for the index (see code below). It does, however, bind the $scope for use in the dropdown via the $scope.$apply.
Something else really odd is if I add an alert, it will start working, like it somehow forces scope back. But using an alert on page load every time just to get the array working is not realistic.
I need to access the array so I can compare against it and get the index so I can set the field value to the correct item currently stored in the database.
Here is the function in my controller. Note that I need to run a sub function to get all the values. This works to create the $scope.termsArray binding that I use in my dropdown, it is the setting of $scope.vm.selectedCategory where the issue is occurring:
var termsArray = [];
// Query Term Store and get terms for use in Managed Metadata picker stored in an array named "termsArray".
function execOperation() {
// Current Context
var context = SP.ClientContext.get_current();
// Current Taxonomy Session
var taxSession = SP.Taxonomy.TaxonomySession.getTaxonomySession(context);
// Term Stores
var termStores = taxSession.get_termStores();
// Name of the Term Store from which to get the Terms. Note, that if you receive the following error "Specified argument was out of the range of valid values. Parameter name: index", you may need to check the term store name under Term Store Management to ensure it was not changed by Microsoft
var termStore = termStores.getByName("Taxonomy1234");
// GUID of Term Set from which to get the Terms
var termSet = termStore.getTermSet("1234");
var terms = termSet.getAllTerms();
context.load(terms);
context.executeQueryAsync(function () {
var termEnumerator = terms.getEnumerator();
while (termEnumerator.moveNext()) {
var currentTerm = termEnumerator.get_current();
var guid = currentTerm.get_id();
var guidString = guid.toString();
var termLabel = currentTerm.get_name();
// Get labels (synonyms) for each term and push values to array
getLabels(guid, guidString, termLabel);
}
// Set $scope to terms array
$scope.$apply(function () {
$scope.termsArray = termsArray;
console.log($scope.termsArray); // DOES NOT LOG ARRAY
});
var currentFacilityIndex = termsArray.map(function (e) { return e.termGUID; }).indexOf(currentFacilityGUID);
console.log(currentFacilityIndex);
$scope.term.selected = termsArray[currentFacilityIndex];
}, function (sender, args) {
console.log(args.get_message());
});
// Get labels (synonyms) for each term and push values to array
function getLabels(termguid, guidString, termLabel) {
var clientContext = SP.ClientContext.get_current();
var taxSession = SP.Taxonomy.TaxonomySession.getTaxonomySession(clientContext);
var termStores = taxSession.get_termStores();
// The name of the term store. Note, that if you receive the following error "Specified argument was out of the range of valid values. Parameter name: index", you may need to check the term store name under Term Store Management to ensure it was not changed by Microsoft
var termStore = termStores.getByName("Taxonomy1234");
// GUID of Term Set from which to get the Terms
var termSet = termStore.getTermSet("1234");
var term = termSet.getTerm(termguid);
var labelColl = term.getAllLabels(1033);
clientContext.load(labelColl);
clientContext.executeQueryAsync(function () {
var labelEnumerator = labelColl.getEnumerator();
var synonyms = "";
while (labelEnumerator.moveNext()) {
var label = labelEnumerator.get_current();
var value = label.get_value();
synonyms += value + " | ";
}
termsArray.push({
termName: termLabel,
termGUID: guidString,
termSynonyms: synonyms
});
}, function (sender, args) {
console.log(args.get_message());
});
}
};
// Execute function
execOperation();
UPDATE: I tried setting the $scope.termsArray = []; per the suggestion below, but it didn't work. What is really odd is that if I have an alert as follows, it somehow forces the console to log/grants me access to the array in the controller.
$scope.$apply(function () {
$scope.termsArray = termsArray;
alert("hey");
console.log($scope.termsArray);
});
I found a bit hard to follow your code.
My first guess would be to instantiate the array with empty value before anything else.
$scope.termsArray = [];
This trick tells Angular that this property exists and will exist at later stage.
I have a single page web app.
For speed, I store each 'page' in the JS.
I have a problem which happens when there is a form on a page. If you fill in the form, and then store it in a js variable, and then retrieve it, the forms values have disappeared?
I use functions like:
var pages_html = {};
var $page = $('#some-page');
store_page($page);
$page.remove();
//some stuff on another page
var $retrieved_page = get_page('some-page');
console.log($retrieved_page.find('#some-input').val())
//consoles log is always blank / ''
function store_page(page){
var page_id = $(page).attr('id');
pages_html[page_id] = $(page);
}
function get_page(page_id){
var page = pages_html[page_id];
return $(page);
}
Everything else seems to work, i can store and retrieve pages as i wish, its just any values of form elements are lost. How can I work around this?
You cannot store it like that. Instead store it as serialized array. which you can then fill it back when needed. serializeArray returns Array of Objects which have name and value
var values = {};
function store_page(page){
var page_id = $(page).attr('id');
pages_html[page_id] = $(page);
values[page_id] = $(page).find("form").serializeArray(); // serialize it
}
function get_page(page_id){
var page = pages_html[page_id];
values[page_id].forEach(function(obj){
page.find('[name=' + obj.name + ']').val(obj.value) // add it again
});
return page; // and then return
}
var cur_storage_unit = $('#storage_unit').val();
$('.size_unit').change(function() {
var id = $(this).attr('id');
//This is how I want it to work, but not sure how
'cur_' + id = $(this).val();
});
The user 'changes' a of class 'size_unit' and id of 'storage_unit'. I want to then set the value of 'cur_storage_unit' to the new value of 'storage_unit'. In italics is how I want it to work, but I'm not sure the syntax of how to get it to work. Thanks!
You're probably better off using an Object, and storing it in there.
var cur_storage_unit = $('#storage_unit').val();
var values = {}; // storage for multiple values
$('.size_unit').change(function() {
var id = this.id;
values['cur_' + id] = this.value; // store this value in the "values" object
});
// Accessible via values object
alert( values["cur_theid"] );
you can create a new property on an object using a string as a key
var myObj = {};
myObj['cur_'+id] = $(this).val();
so in your case you would want an object with a known name where you can add dynamically named properties.
If it's global you can do window['cur_'+id];