I have new inputs for a multidimensional array. The original inputs that are already defined are displayed correctly when called upon but the new inputs write as "undefined". I think it is recognizing the new inputs as variables. How do you get them to show up as a string?
var original = new Array(); //this is the array
function input(title, artist, ddate, genre, picsrc) {
this.Title = title;
this.Artist = artist;
this.Ddate = parseInt(parseFloat(ddate));
this.Genre = genre;
this.Picsrc = picsrc;
}
original[0] = {title:"Hope II", artist:"Gustav Klimt", ddate:1907, genre:"Art Nouveau", picsrc:"gustav.jpg"}; //and so on
Values that are added to the array are taken from a form.
function addit(form) {
G = form.Title.value //as a test
original[original.length++] = new input(form.Title.value, form.Artist.value, form.Ddate.value, form.Genre.value, form.Picsrc.value)
alert("your entry has been added")
alert(G) //value shows up in the alert
}
but when it is called back in this function:
$("#info").html(original[currentrecord]["title"]+"<br /><h2>"+original[currentrecord]["artist"]+"</h2>"+original[currentrecord]["ddate"]+"<br />"+original[currentrecord]["genre"]);
everything is being written as "undefined".
I am assuming that the data is successfully being added to the array, but maybe not in the right format?
I prefer using dot notation, but it's not a requirement.
The real issue is: JavaScript is case sensetive.
I would do it like this:
original[currentrecord].Title
original[currentrecord].Artist
and so on...
At one place in your code you are using all lowercase (when initializing original[0]), but in the constructor function you are using uppercase for the first letter.
Related
Im trying to update an SP.Listitem withholding an spUser with another user with the use of JSOM. See codesnippet bellow
// Query the picker for user information.
$.fn.getUserInfo2 = function () {
var eleId = $(this).attr('id');
var siteUrl = _spPageContextInfo.siteServerRelativeUrl;
var spUsersInfo = GetPeoplePickerValues(eleId);
var clientContext = new SP.ClientContext(siteUrl);
var oList = clientContext.get_web().get_lists().getByTitle('VLS-dokument');
var itemArray = [];
for(i=0;i<$.miniMenu.i.results.length;i++)
{
var item = $.miniMenu.i.results[i];
var oListItem = oList.getItemById(item.Id);
oListItem.set_item('Informationsägare', SP.FieldUserValue.fromUser(spUsersInfo.Key));
oListItem.update();
itemArray.push(oListItem);
clientContext.Load(itemArray[itemArray.Length - 1]);
}
clientContext.executeQueryAsync(Function.createDelegate(this, function () { alert(""); }), Function.createDelegate(this, function () { alert(""); }));
return spUsersInfo; //.slice(0, -2)
}
spUsersInfo contains the user obj, peoplePicker.GetAllUserInfo()
The return off SP.FieldUserValue.fromUser(spUsersInfo.Key) to be the problem since the app crash reaching that line oListItem.set_item('Informationsägare', SP.FieldUserValue.fromUser(spUsersInfo.Key));
What part of the user obj is supposed to be passed into SP.FieldUserValue.fromUser(spUsersInfo.Key) if not the key?
Is there another way to do it?
People picker columns are really just lookup columns, looking up against the site collection's user information list. You can set a lookup column either by specifying the ID of the desired item in the lookup list, or by creating a special lookup field value object (letting SharePoint do the work of finding the ID, given the desired text value).
According to the documentation the value passed to SP.FieldUserValue.fromUser() should be the user's name as a string. In practice, this should be the user's display name from the user information list.
So if you don't know the user's lookup ID, but do know their display name, you would use this: oListItem.set_item('Informationsägare',SP.FieldUserValue.fromUser(username));
If you didn't know the user name, but did know the lookup ID of the user, you could instead pass that number to item.set_item() directly, i.e. oListItem.set_item('Informationsägare',lookupId);.
If the spUsersInfo.Key value from your GetPeoplePickers() method is in the format of i:0#.w|Cool Person then you can split that value and just get the string Cool Person to feed into SP.FieldUserValue.fromUser().
i need to print an array of json object which are been entered by user through text box, this function is executed by button click. i need to store all the string localy that are entered by the user in text box. and display it in my console in this formate [{"aaa"},{"bbb"},{"ccc"}]
<!DOCTYPE html>
<html>
<body>
Enter the string :
<input type="text" id="names">
<button onclick="myFunction()"> Click Me</button>
<script>
function myFunction(){
var myNames = new Array();
myNames = document.getElementById("names").value;
this.names = myNames;
localStorage["myNames"] = JSON.stringify(myNames);
console.log(JSON.stringify(myNames));
var name = JSON.parse(localStorage["myNames"]);
console.log(name);
};
</script>
</body>
</html>
Currently this code just print the data like this "aaa", if i add another data bbb, only the 2nd data "bbb"is displayed. i want all the data to be viewed in this formate [{"aaa"},{"bbb"},{"ccc"}] or even like this [{"name":"aaa"},{"name":"bbb"},{"name":"ccc"}] .
Could someone help me?
That's not related to localStorage or JSON.
When you perform myNames = document.getElementById("names").value; you replace the empty Array with a string.
You may use .push on array : https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/push
And create an object then pushing it, for example myObj = {'v': value}; myArray.push(myObj);
you can try this:
var myNames = []
function myFunction(){
var oldItems = JSON.parse(localStorage.getItem('myNames')) || [];
newItem = {"name":document.getElementById("names").value};
oldItems.push(newItem);
localStorage.setItem("myNames", JSON.stringify(oldItems));
console.log(JSON.parse(localStorage.getItem("myNames")));
};
If you want to preserve the previously entered data, you have to retrieve them first and alter them.
Below are two functions; one that adds an item to the array. If the array isn't present yet (so no data has been entered previously), it creates a new array for you.
Afterwards it stores the data in the localStorage again.
Upon entering new data that needs to be added, it first retrieves any previous entries and alters that. Then it stores again and so on and so on.
function myFunction(){
var myNames = localStorage.getItem('myNames'),
parsedArray = JSON.parse(myNames),
valueToAdd = document.getElementById("names").value;
// Add the new item to the original array.
parsedArray = addToArray(parsedArray, valueToAdd);
localStorage.setItem('myNames', JSON.stringify(parsedArray));
console.log(parsedArray);
};
function addToArray (array, item) {
// If the array doesn't exist, create one
if (!array) {
array = [];
}
// Add the item to the array.
array.push(item);
return array;
};
so I have a JSON object returned from a webservice. Now I want to:
get a subset which matches a categoryTitle i pass as parameter (this seems to work)
from my filtered resultset I want to get another array of objects (helpsubjects), and for each of this subjects I want to extract the SubjectTitle.
Problem: It seems my Array of HelpSubjects does not exist, but I can't figure out why and hope you could help.
Perhaps this piece of commented code makes it more clear:
$.fn.helpTopicMenu = function (data) {
that = this;
var categoryContent = contents.filter(function (el) {
return el.CategoryTitle == data.categoryTitle;
});
debug('categorys Content: ', categoryContent); //see below
var container = $('#subjectList');
var subjectList = categoryContent.HelpSubjects;
debug('Subjects in Category: ', subjectList); // UNDEFINED?!
$.each(subjectList, function (i, item) {
container.append(
$('<li></li>').html(subjectList[i].SubjectTitle)
);
});
the line debug('categorys Content: ', categoryContent); returns the following object as shown in the picutre (sadly I can't add a picture directly to the post yet, so here's the link): http://i.stack.imgur.com/0kKWx.png
so as I understand it, there IS actually a HelpSubjects-Array, each entry containing a SubjectTitle (in the picture there actually is only one entry, but I need to have the Artikel einfügen as my html.
Would be great if you can help me.
The variable categoryContent set is an array of objects.
Try debugging categoryContent[0].HelpSubjects and see if you can access the property. If so, you can also loop this array if need be.
I have the following code to extract values from a JSON response. What I am trying to do is store the data in a similar way to how you would with an associative array in php. Apologies for the code being inefficient. The array comments written down are how I would like it to look in the object.
$.each(responseData, function(k1,v1){
if(k1 == "0"){
$.each(v1, function(k2,v2){
$.each(v2, function(k3, v3){
if(k3 == "val"){
//store in object here
//Array1 = array("time"=>k2, "iVal"=>v3)
console.log(k3 + v3 + k2);
}else{
//Array2 = array("time"=>k2, "aVal"=>v3)
console.log(k3 + v3 + k2);
}
});
});
}
});
So all the information is there but I am not sure how to store each instance for the values in an object. I did try store it like this:
//obj created outside
obj1.date = k2;
obj2.iVal = v3;
But doing this clearly overwrote every time, and only kept the last instance so I am wondering how can I do it so that all values will be stored?
Edit: Added input and output desired.
Input
{"0":{"18.00":{"iVal":85.27,"aVal":0.24},"19.00":{"iVal":85.27,"aVal":0.36},"20.00":{"iVal":0,"aVal":0}}, "success":true}
Desired output
array1 = {"time":"18.00", "iVal":85.27},{"time":"19.00", "iVal":85.27},{"time":"20.00", "iVal":0}
array2 = {"time":"18.00", "aVal":0.24},{"time":"19.00", "aVal":0.36},{"time":"20.00", "aVal":0}
try this :
var g1=[];
var g2=[];
for ( a in o[0])
{
g1.push({time:a , iVal:o[0][a]['iVal']})
g2.push({time:a , aVal:o[0][a]['aVal']})
}
http://jsbin.com/qividoti/3/edit
a json response can be converted back to a js object literal by calling JSON.parse(jsonString) inside the success callback of your ajax call.
from then on there is no need for iterating over that object since you navigate it like any other js object which is can be done in two ways either
the js way -> dot notation
var obj = JSON.parse(jsonStirng);
var value = obj.value;
or like a php array
var value = obj["value"];
I'm trying to achieve a function that makes the user able to save a mathematical formula that uses static variables that I've already created and save them with Local Storage.
Then the script fetches that formula from the Local Storage, does the math and displays the results on a table.
I have everything in order, except the fetching part;
as localStorage.getItem() returns a string, and converting it with parseFloat()/parseInt() only returns the first integer or NaN.
Both of this messes up the expected the results.
Is there any way I can get Objects from localStoage that contains both integers and variables?
Heres an example of a formula that should work, fetched by 5 localStorage.getItem() requests.
avgFrags*250
avgDmg*(10/(avgTier+2))*(0.23+2*avgTier/100)
avgSpots*150
log(avgCap+1,1.732)*150
avgDef*150
Any ideas or alternatives?
EDIT:
Each line represents the output of a getItem() request;
form_frag = localStorage.getItem('formula_frag');
form_dmg = localStorage.getItem('formula_dmg');
form_spot = localStorage.getItem('formula_spot');
form_cap = localStorage.getItem('formula_cap');
form_def = localStorage.getItem('formula_def');
localStorage store in a key-value store where every value is pushed to a string. If you are certent that you are handling "integers" you can push the string to a number:
var avgFrags = +localStorage.getItem('avgFrags'); // The + infront pushes the string to number.
I'm not completely sure that I understand your question.
(+"123") === 123
You can convert easily convert your strings to functions if you know the variable names before hand using Function(). The first parameter(s) are your function arguments and the last is your function body.
var func1 = Function('avgFrags', 'return avgFrags * 250;');
This is equivalent to:
function func1(avgFrags) {
return avgFrags * 250;
}
Known Function Signature
If you know what variable names will be used for each item in local storage then it should be easy for you to do what you want with function:
// from your edited question
form_frag = localStorage.getItem('formula_frag');
form_dmg = localStorage.getItem('formula_dmg');
// ... create functions
var fragsFunc = Function('avgFrags', form_frg );
var dmgFunc = Function('avgDmg', 'avgTier', form_dmg );
// ... get frags
var frags = fragsFunc (10); // frags = 2500; // if sample in storage
Unknown Function Signature
Now if you have a limited amount of variable names and you don't know which ones will be used with each function then you can do something like:
var avgFrags, avgDamage, avgTier, avgSpots, avgCap, avgDef;
// ... get from storage
form_frag = localStorage.getItem('formula_frag');
form_dmg = localStorage.getItem('formula_dmg');
// ... create functions
var fragsFunc = Function('avgFrags', 'avgDamage', 'avgTier', 'avgSpots', 'avgCap', 'avgDef', form_frag);
var dmgFunc = Function('avgFrags', 'avgDamage', 'avgTier', 'avgSpots', 'avgCap', 'avgDef', form_frag);
// ... get frags, only the first argument is used, but we don't know that.
var frags = fragsFunc (avgFrags, avgDamage, avgTier, avgSpots, avgCap, avgDef); // frags = 2500; // if sample in storage
You can make this simpler by having just one variable passed into the function which is an object that holds all of the arguments that can be passed to the function. Just have to make sure that the function writer uses that object.
var settings = {
avgFrags: 10,
avgDamage: 50,
// ...
};
var fragsFunc = Function('s', 's.avgFrags * 250');
var frags = fragsFunc (settings);
Getting parts with an regex
I am assuming that the above will get the job done, that you don't really want an object with variable names and numbers and operators.
If you just need the variable names and numbers (and operators) you can use a regex for that.
([a-z_$][\w\d]*)|([0-9]*\.?[0-9]+)|([^\w\d\s])
You can use that to create an array with each part. Also each part is grouped so you know which is a variable name, which is a number, and which is an other (parenthesis or operator)
var re = /(\w[\w\d]*)|([0-9]*\.?[0-9]+)|([^\w\d\s])/g,
match,
results;
while ((match = re.exec(localStorage.getItem('formula_frag'))) {
results.push({
text: match[0],
type: (match[1]) ? 'var' | (match[2]) ? 'number' : 'other'
})
}
You can view the output of the regex with your sample data using REY.
Yes you can set Objects in localstorage
Here is the fiddle for that - http://jsfiddle.net/sahilbatla/2z0dq6o3/
Storage.prototype.setObject = function(key, value) {
this.setItem(key, JSON.stringify(value));
}
Storage.prototype.getObject = function(key) {
var value = this.getItem(key);
return value && JSON.parse(value);
}
$(function() {
localStorage.setObject('x', {1: 2, 2: "s"})
console.log(localStorage.getObject('x'));
});