Trying to use input from prompt as object value within a function - javascript

Please be aware that I have only learned how to use objects this morning, so this is mainly an exercise to play around with this.
I was able to set up an array with a list of students. Each student is an object with multiple properties. I was also able to add another property and value to each object within the array using a for loop.
What I'm trying to do now is prompt the user to enter an object name "student1, student2, etc." I'm trying to use the value of that prompt, saved as var studentSelected, in the function reportStudentInfo(info).
What does work: If i get rid of the variable "selectedStudent", and I specifically decide to put in an object value student1, student2, etc. it works as expected.
What I don't understand:
I'm guessing the value of the prompt changes to a string from the prompt and it seems to mess up the value of what the object is, even though the prompt input might be: "student1" the function isn't reading it as student1. It returns an undefined value for each of the object property values.
I really hope I asked a clear enough question. Thanks for any help.
Logan
link to JSFiddle: https://jsfiddle.net/lwood3499/aevsbrk8/
var selectedStudent = prompt("Which student do you want to see the results for Test #1?");
reportStudentInfo( selectedStudent.name + " : " + selectedStudent.test1 );

After
var selectedStudent = prompt("Which student do you want to see the results for Test #1?");
selectedStudent is a string entered at the prompt. It does not have name or test1 properties.
If selectedStudent object already exists, you can do
var selectedStudent.name = prompt("Which student do you want to see the results for Test #1?");
or
var studentName = prompt("Which student do you want to see the results for Test #1?");
Update:
var selectedStudent = prompt("Which student do you want to see the results for Test #1?");
var found = null;
for (var iter = 0; iter < list.length; iter++) {
if (selectedStudent == list[iter].name) {
found = list[iter];
break;
}
}
if (found) {
reportStudentInfo(found.name + " : " + found.test1 );
} else {
alert(selectedStudent + " not found");
}

Related

ValueIterator.toArray().indexOf() returns unexpected results?

UPDATE: this is NOT a question on javascript alone, but related to the javascript implementation on the MarkLogic platform.
As the title of this question points out it is about the specific behaviour of the ValueIterator that is returned by the xdmp.userRoles() function.
I am trying to see if a user has a certain role in MarkLogic Security database, therefor I have done this :
declareUpdate();
var pid = '7610802';
// TODO validate that user can do this
var spo = 'scc-proj-' + pid + '-owner';
var spm = 'scc-proj-' + pid + '-member';
var spam = 'scc-proj-' + pid + '-adv-member';
// we need the security db Ids of these roles
var spoId = xdmp.role(spo);
var spamId = xdmp.role(spam);
var acceptedRoleIds = [spamId,spoId];
// get roleIds from sec db for this user
var userRoleIds = xdmp.userRoles('scc-user-1');
// map ValueIterator to array
var userRoleIdsArray = userRoleIds.toArray();
Now the userRoleIdsArray holds ids as unnsigned long like this:
[
"1088529792688125909",
"1452323661308702627",
"10258509559147330558",
"10161853410412530308",
"6677433310138437512",
"12773061729023600875",
"7482704131174481508",
"3191093315651213021", <<<<< this is the one!!!
"5126952842460325403",
"7089338530631756591",
"15520654661378671735",
"13041542794130379697"
]
Now indexOf() gives me -1 aka not found
userRoleIdsArray.indexOf(3191093315651213021);
OR
userRoleIdsArray.indexOf("3191093315651213021");
Gives :
-1
While
userRoleIdsArray[7]==3191093315651213021;
Gives :
true
What am I missing here? Is this not the way to use indexOf() ?
UPDATE >>> Stuff below was 'on-the-side' but turns out to be distracting from the above core question. The behaviour below is answered by #DaveCassel's comment.
btw on the created array acceptedRoleIds it is even more strange:
acceptedRoleIds.indexOf(spoId);
works
acceptedRoleIds.indexOf(3191093315651213021);
does not?
Could this large number error in javascript be relevant?
You want to find a String, not a number. Use: userRoleIdsArray.indexOf("3191093315651213021");
This works:
var array = [
"1088529792688125909",
"1452323661308702627",
"10258509559147330558",
"10161853410412530308",
"6677433310138437512",
"12773061729023600875",
"7482704131174481508",
"3191093315651213021",
"5126952842460325403",
"7089338530631756591",
"15520654661378671735",
"13041542794130379697"
];
var n = array.indexOf("13041542794130379697");
document.write(n);
output: 11
The mismatch is that ValueIterator.toArray() returns an array of Values (Value[]). When you call .indexOf, you're passing in a string or an unsignedLong rather than a value. Because the types don't match, .indexOf() doesn't report a match.
You can solve the problem by iterating through the loop. Note that I use the '==' operator rather than '==='; the type conversion is needed.
// get roleIds from sec db for this user
var userRoleIds = xdmp.userRoles('my-user');
// map ValueIterator to array
var userRoleIdsArray = userRoleIds.toArray();
var target = 15520654661378671735;
var index = -1;
for (var i in userRoleIdsArray) {
if (userRoleIdsArray[i] == target) {
index = i;
}
}
index

Display the results of an array on another page

I'm trying to load an array from one page and then have the results appear on another using javascript/jQuery. So a user will make a selection from a dropdown. Based on this dropdown the "customers" address, phone, email, etc. will appear in a text field. I'm trying to store those results in to the array (name | address | etc in one index of the array), display the result on the second screen, and then allow the user to add more names if necessary.
At the moment I'm trying to use localStorage to store the values and then JSON.stringify to convert the results so they can be stored in the array.
I think these are all of the pertinent lines:
var customerArray = [];
var getName = $('#DropDownList1').val();
var getAddress = $('#DataList1').text().trim();
var getPhone = $('#DataList2').text().trim();
var getEmail = $('#DataList3').text().trim();
//store the variables
localStorage.setItem("name", getName);
localStorage.setItem("address", getAddress);
localStorage.setItem("phone", getPhone);
localStorage.setItem("email", getEmail);
//user will click #btnAdd to add the customers information
//into customerArray[]
$("#btnAdd").click(function () {
var setName = localStorage.getItem("name");
var setAddress = localStorage.getItem("address");
var setPhone = localStorage.getItem("phone");
var setEmail = localStorage.getItem("email");
var post = setName + setAddress + setPhone + setEmail;
if (customerArray.length == 0) {
customerArray[0] = post;
} else {
for (var i = 1; i < customerArray.length; ++i) {
//store results of 'post' into the array
customerArray.push(post);
localStorage.setItem("storedArray",JSON.stringify(customerArray));
}
}
}); //end #btnAdd click event
Form here the 2nd page will load with a text field that will (should) display the results of the array (customerArray). Unfortunately I can only get 1 value to appear.
At the moment this is the block being used to display the results:
$('#tbContactList').val(JSON.parse(localStorage.getItem("storedArray")));
If it matters I'm writing the application using Visual Studio Express 2012 for Web. The data that initially populates the customers information comes from a database that I've used ASP controls to get. I'm confident there is a perfectly simple solution using ASP/C# but I'm trying to solve this problem using javascript/jQuery - I'm more familiar with those languages than I am with C#.
Thank you.
Use Array.join() to turn your array into a string to store.
Then use Array.split() to turn your string back into an Array.
Example
var arr=['name','email','other'];
var localStorageString=arr.join(',');
localStorage.setItem('info',localStorageString);
var reassemble=localStorage.info.split(',');
for(var i=0;i<reassemble.length;i++){
document.body.innerHTML+=reassemble[i]+"<br/>";
}
http://jsfiddle.net/s5onLxd3/
Why does the user have to leave the current page though? IS a tabbed/dynamic interface not an option?

Javascript: Using user input to search an array of arrays

Maybe I'm structuring this code wrong (first time working with Javascript) but I want to take user input and search an array of arrays to check if an array with that name exists.
I first tried using the eval() function which I've been told isn't good but it works when there is a match, failing when a match that doesn't exist though.
The basic premise of the program is there is an array containing locations which are subsequently arrays containing food items. The user enters the name of a food item and where they want to put it and it will create an object of food, insert that object into the right location within the arrays, and also input the item onto a list displayed in html.
Here's all the code so far:
var fridge = [];
var freezer = [];
var pantry = [];
var locations = [fridge, freezer, pantry];
function Food(name, location, locationName){
this.name = name;
this.location = location;
this.locationName = locationName;
this.displayName = function(){
alert(this.name);
};
};
function createFood(){
var name = prompt("Enter the items name:");
var locationName = prompt("Enter a location to store it:")
var location = eval(locationName);
while(locations.indexOf(location) == -1){
alert("This is not an actual location.");
locationName = prompt("Please enter another location:");
location = eval(locationName);
};
var x = new Food(name, location, locationName)
function insertFood(Food){
var a = locations.indexOf(Food.location);
locations[a].push(Food);
var list = document.getElementById(Food.locationName + "_items");
var li = document.createElement("li");
li.innerHTML = Food.name;
list.insertBefore(li, list.lastChild);
};
insertFood(x);
};
Please let me know if this is structured wrong cause this was my idea for structuring at first glance.
Thanks!
As suggested above, it would be best to make locations an object, so that you can have a key (a string) pointing to the array with the same name.
var fridge = [];
var freezer = [];
var pantry = [];
var locations = {
"fridge":fridge,
"freezer":freezer,
"pantry":pantry
};
The benefit of this is that you don't need to have a locationName, since it never really comes into play. All you would need is to check if the locations object has a property by the same name as the user input, using the native hasOwnProperty function. Something like:
if(!locations.hasOwnProperty(userInputLocation))
alert("That is not a designated location");
Then your Food constructor also becomes simpler, and needs only name and location properties:
function Food(name, location){
this.name = name;
this.location = location;
}
You can also then call any specific location directly by its name (if you're going to declare it globally as you did in your code), or more appropriately (if you declare the arrays inside the object as in SGD's code) by locations[location], where location is just a string holding either "freezer" or "pantry" or "fridge". You can also call the array via locations[someFood.location].
Anyway I am not much for prompts and alerts (let alone eval), so I created a jsBin using input fields, you can check it out here: http://jsbin.com/pamoquwuhu/1/edit
edited to add:
If the goal is that you later want to find food by its name in all the locations it is saved in, it would be best to add/push foodObj.name instead of the whole foodObj in locations[location]. Then you can use the native for(property in object) loop on the locations object to see where all a given food might be stored, and push it into a results array. So your findFood function might contain the following (assuming food is the user input string of of food name to search for:
var results = [];
for(var loc in locations){ // loops through the property names in `locations`
if(locations[loc].indexOf(food)>=0)
results.push(loc);
}
if(!results.length){
alert(food+' was not found');
else
alert(food+' was found in '+results.toString());
Assuming the same food can be stored in multiple locations and that you want to find a given food by its name, your food object's location property would become less important (or possibly useless).
You are using Food as function/constructor and as parameter name (that should not be the issue however but can cause trouble later) and you are never calling insertFood. Also locations should rather be object than array so that you can access the sub arrays as you do in your code.
var locations = {fridge : [], freezer:[], pantry:[]];
function Food(name, locationName){
this.name = name;
this.locationName = locationName;
this.displayName = function(){
alert(this.name);
};
};
function createFood(){
var name = prompt("Enter the items name:");
var locationName = prompt("Enter a location to store it:")
while(locationName in locations){
alert("This is not an actual location.");
locationName = prompt("Please enter another location:");
};
var x = new Food(name, locationName)
function insertFood(food){
locations[food.locationName].push(food);
var list = document.getElementById(food.locationName + "_items");
var li = document.createElement("li");
li.innerHTML = food.name;
list.insertBefore(li, list.lastChild);
};
// call the method now?
insertFood(x);
};
createFood();

How to generate an array of arrays in Javascript?

So given:
var person = {name: "", address: "", phonenumber: ""}
I want to create a loop to receive user input (until they decide they don't want to input anymore information and input nothing or click cancel). I'd also like to use the person object as a prototype.
So I guess an object just to store the name/address/phone number of an arbitrary number of people. My logic for this would be to dynamically add an entire array to an object for every iteration of my loop. My code looks something like this:
var person = {name: "", address: "", phonenumber: ""}
var customer = []; //used to store each person
var input = "x";
//loop prompting user to input name/address/phone number
for(var i = 0; input != ""; i++){
var input = prompt("Input separated by commas");
//example input: mike, main, 123456789
var results = input.split(", "); //create an array from the input
//move input into the person array.
//person to look like {name = "mike", address = "main", phone = "123456789"}
person.name = results.shift();
person.address = results.shift();
person.phone = results;
customer[i] = person;//store the person array into the customer array.
}
I've been trying to dynamically generate something like this:
customer =
[{name, address, phone},
{name, address, phone},
{name, address, phone}]
and then be able to access it and print it. i've been trying to access it with
console.log(customer[0].phone);
unfortunately im getting an error.
sorry for my error, console.log prints nothing so it seems like there's nothing stored in customer[0].phone.
i can't get access to any of the data that i've prompted the user for and saved in variables. when i use the alert function all i get is a blank box. whenever i try to print customer i get the message [object Object]or something along those lines
var customer = [];//create array
var person = {};// create object
var input = prompt("...");//your prompt
var results = input.split(", "); //create an array from the input
person.name = results[0];//add result with 0 index
person.address = results[1];//add result with 1 index
person.phone = results[2];//add result with index 2
customer[0] = person;//add the person object to the array.
The above code should do as you wish. I'm having a hard time seeing why you would iterate a prompt to the same user?? So try this first then go on.
http://jsfiddle.net/zkc2swmp/1/
Don't go irratating your users with prompt boxes, use a form. Also don't iterate something like that, and your condition in the for loop basically creates an infinite loop which is also bad
My code could be a lot better, such as if conditions, and exactly how to use this with a form. Though frankly it seems as though you are far from that. So I've started you off, try it and see if you can implement this the way you want, then comment with suggestions for helping you do something else.
First of all, every time you are assigning person to customer i.e.
customer[i] = person;
all other objects are getting modified as your breaking point is input== "" so all objects are modified with null values.
in start you are defining property as "phonenumber" and in the end u r putting value in "phone".
correct code shud be :
var customer = []; //used to store each person
var input = "x";
//loop prompting user to input name/address/phone number
for(var i = 0; input != ""; i++){
var input = prompt("Input separated by commas");
//example input: mike, main, 123456789
var results = input.split(", "); //create an array from the input
var person = {};
person.name = results.shift();
person.address = results.shift();
person.phone = results;
customer[i] = person;//store the person array into the customer array.
}

JS merge duplicates in array into "[num]x string"

I'm sure that this already has a duplicate, but I couldn't find one because I had no idea on how to phrase this question. Basically, I have a JS array. The user can add items to it from a dropdown menu. This array is then fed into a textarea. The user can input the same value more than once. If they have two of the same string in the array, I would like to delete both and replace it with '2x string'. Also, if '2x string' and 'string' both exist, then they will be made into '3x string', etc, etc. Thanks in advance for answering. I really appreciate it. I tried to keep it as general as possible so that others with the same problem can get help from this too.
JS:
var newfish = 'foo';
var oldtextareacontent = 'foo';
var fish = new Array();
var fishformatted = new Array();
function addfish(){
//form is never submitted so as not to refresh page
oldtextareacontent = document.getElementById("stock").value;
newfish = document.getElementById("fish").options[document.getElementById("fish").selectedIndex].text;
fish.push(newfish);
fishformatted = fish.join("\n");
document.getElementById("stock").innerHTML = "Your stock:
" + fishormatted;
}

Categories

Resources