Javascript adding 2nd dimension not returning results - javascript

I have a site made as shown in this jsfiddle:
http://jsfiddle.net/bAz3y/
$.getJSON('eventbrite.json', function(data) {
var events = [];
var j = 0;
for (var i in data) {
events[i][0] = data[i].event.title;
}
$('.btn-lg').click(function() {
$('#tester').replaceWith("<div id='tester'>" + events[j][0] + "</div>");
j = j + 1;
})
$("div.swiper").on("swipe",function() {
$('#tester').replaceWith("<div id='tester'>" + events[j][0] + "</div>");
j = j + 1;
})
});
I'm trying to get the 2nd dimension to store the event title, so that I can then add event date and distance in events[j][1] and events[j][2].
However, adding the second dimension (ie the events[i][0]) means no results are returned.

The problem is the for loop, events[i] is undefined so events[i][0] will fail
1.Solution is
for (var i in data) {
events[i] = [data[i].event.title, data[i].event.some];
}
2.Another is to use $.each() and do
var events = [];
var j = 0;
$.each(data, function(_,item){
events.push([item.event.title, data[i].event.some])
});
3.A third way is to use $.map()
var j = 0;
var events = $.map(data, function (item) {
return [[item.event.title, data[i].event.some]]
});

Related

How do I create different button for each item in an array / JavaScript

Here's my code:
var never = [1,2,3,4,7];
function please () {
for (var i = 0; i < never.length; i++) {
document.getElementById("more").innerHTML = "<button>" + never[i] + "</button>";
}
}
I have a button in my HTML that invokes this function but it only creates a button for the last item (7). How can I create a different button for each one of the items in the array? Any help is appreciated.
The best way is to append created buttons in container.Each by each
var never = [1,2,3,4,7];
function please () {
var more=document.getElementById("more");
for (var i = 0; i < never.length; i++) {
var butt=document.createElement("button");
butt.innerHTML=never[i];
more.appendChild(butt);
}
}
By appending to innerHTML instead of assigning, like
var never = [1,2,3,4,7];
function please () {
for (var i = 0; i < never.length; i++) {
document.getElementById("more").innerHTML += "<button>" + never[i] + "</button>";
}
}
please();
<div id="more">
</div>

Having Trouble Parsing Results of Array

I'm having a bit of trouble trying to parse the results of an array and print to the console. It's a two part problem actually. When I build the array it's adding "undefined" to the results. When I try to loop through the individual strings in the array it isn't parsing, just returning the full array object.
What I'm trying to do is collect all the field values selected from a list view and write them to another child list as separate items. When displaying results in a console it shows as an object array. When I run the typeof method against it I believe it shows as a string.
To reiterate, why am I getting undefined and why is my array not printing to console correctly. Below is an example of what is being returned thus far (when two records are selected) and my code.
Results:
undefinedDaffy DuckBugs Bunny
undefined
Code:
// Grabs selected items from getSelected function and passes parameters to writeSelected function
function callAccepted() {
getSelected().done(function(varObjects) {
for (var k in varObjects) {
console.log(varObjects[k]);
}
}); // End getSelected
} // End callAccepted
// Grabs selected items, accepts input from callAccepted or callRejected functions
function getSelected() {
var dfd = $.Deferred(function(){
var ctx = SP.ClientContext.get_current();
var clientContext = new SP.ClientContext();
var targetList = clientContext.get_web().get_lists().getByTitle(ListName);
var SelectedItems = SP.ListOperation.Selection.getSelectedItems(ctx);
var items = [];
var arrItems = [];
for (var i in SelectedItems) {
var id = SelectedItems[i].id;
var item = targetList.getItemById(id);
clientContext.load(item, "Title");
items.push(item);
} // End for
clientContext.executeQueryAsync(
function(){ // Return to button click function
var itemLength = 0;
var itemObjects = [];
for (var j = 0; j < items.length; j++) {
itemObjects = items[j].get_item("Title");
itemLength += itemObjects;
arrItems.push(itemObjects);
}
dfd.resolve(arrItems, itemLength);
},
function(){ // Return to button click function
dfd.reject(args.get_message());
}
); // End ClientContext
}); // End dfd
return dfd.promise();
} // End getSelected
Why are you writing "var itemObjects;" in 1 line and add one string "itemObjects += items[j].get_item("Title");" in another? There'll be only 1 string anyway, so when you change those 2 lines into one, "undefined" should disappear:
function callAccepted() {
getSelected().done(function(varObjects, iLength) {
// Stuff
for (var k = 0; k < iLength; k++) {
console.log(varObjects[k]);
}
}); // End getSelected
} // End callAccepted
// Get user information function
function getSelected() {
var dfd = $.Deferred(function(){
var ctx = SP.ClientContext.get_current();
var clientContext = new SP.ClientContext();
var targetList = clientContext.get_web().get_lists().getByTitle(ListName);
var SelectedItems = SP.ListOperation.Selection.getSelectedItems(ctx);
var items = [];
var arrItems = [];
for (var i in SelectedItems) {
var id = SelectedItems[i].id;
var item = targetList.getItemById(id);
clientContext.load(item, "Title");
items.push(item);
} // End for
clientContext.executeQueryAsync(
function(){ // Return to button click function
for (var j = 0; j < items.length; j++) {
var itemObjects = items[j].get_item("Title");
var itemLength = items.length;
arrItems.push(itemObjects);
}
dfd.resolve(arrItems, itemLength);
},
function(){ // Return to button click function
dfd.reject(args.get_message());
}
); // End ClientContext
}); // End dfd
return dfd.promise();
} // End getSelected
The reason for this is that after creating the variable without any value, it's undefined, so += 'Unicorn' will give us ugly 'UndefinedUnicorn'. If you wish to make variable for this purpose, write it "var x = ''".
And if - for example - you want to sum length of all "items", then this one function should look like:
function(){ // Return to button click function
var itemLength = 0;
for (var j = 0; j < items.length; j++) {
var itemObjects = items[j].get_item("Title");
itemLength += itemObjects;
arrItems.push(itemObjects);
}
dfd.resolve(arrItems, itemLength);
}
But I'm not exactly sure what are you trying to get here.

dat.GUI create multiple buttons with same name

I try to use dat.GUI to create multiple buttons all with same name "ShowCoord", is this possible? What I have currently is:
for (i = 0; i < overlay.numElements; i ++)
{
var length = overlay.elementNumVertices[i];
var subObj = {
'name' : overlay.elementNames[i],
'index' : i,
'numVertices': overlay.elementNumVertices[i],
"ShowCoord" : function(){
console.log("i is " + subObj['index']);
var verts = overlay.elementVertices[i];
for(var j = 0; j < subObj['numVertices']; j ++)
{
console.log("The coordinates are " + verts[3*j] + ", "+ verts[3*j+1] +", "+verts[3*j+2]);
}
}
};
subObjArray.push(subObj);
}
for(i = 0; i < subObjArray.length; i ++)
{
var currObj = subObjArray[i];
var subGui = gui.addFolder(currObj['name']);
subGui.add(currObj, 'numVertices');
subGui.add(currObj, "ShowCoord");
}
I now have the correct currObj['name'] and currObj['numVertices'] displayed. But all the "ShowCoord" button only contains information of the very last subObj (so console.log("i is " + subObj['index']) will print out 148 every time even if I click different button). How can I make it work? Thanks a lot!
Try moving subGui outside the for loop and modifiy you code so that you don't reassign subGui varialbe.
var subGui = new dat.GUI();
for(i = 0; i < subObjArray.length; i ++)
{
var currObj = subObjArray[i];
subGui.addFolder(currObj['name']);// <--- work on this line
subGui.add(currObj, 'numVertices');
subGui.add(currObj, "ShowCoord");
}
Otherwise it will always be redefined with the last iterated element of for loop
Note: This is just a hint, I can't conclude more from your code.

Problems with multidimensional array and loops

This script crashes randomly with the message "unable to get property .length of undefined or null reference" referring to "matched_array_pics.length". It crashes for sure if I clone, append the same image twice to the #train div.
$(document).ready(function () {
var starting_pics = ["AN.gif", "CN.gif", "EN.gif", "GN.gif"];
var an_array_pics = ["CN.gif", "EN.gif", "GN.gif", "AN.gif"];
var cn_array_pics = ["EN.gif", "GN.gif", "AN.gif", "CN.gif"];
var en_array_pics = ["GN.gif", "AN.gif", "CN.gif", "EN.gif"];
var gn_array_pics = ["AN.gif", "CN.gif", "EN.gif", "GN.gif"];
var grand_array_pics = [an_array_pics, cn_array_pics, en_array_pics, gn_array_pics];
var i = 0;
for (i = 0; i < starting_pics.length; i++) {
$("<img/>").attr("src", "images/" + starting_pics[i]).load(function () {
$(this).appendTo("#main");
$(this).addClass("pics");
});
}
$("#main").on("click", ".pics", function () {
var j = $(".pics").index(this); // gets the index for the matched_array_pics...
console.log(j);
$("#sidebar .pics").remove();
$(this).clone().appendTo("#train");
$(this).clone().appendTo("#sidebar");
$("#main .pics").remove();
var matched_array_pics = grand_array_pics[j]; // ... in grand_array_pics.
var k = 0;
for (k = 0; k < matched_array_pics.length; k++) {
$("<img/>").attr("src", "images/" + matched_array_pics[k]).load(function () {
$(this).appendTo("#main");
$(this).addClass("pics");
});
}
});
}); //end ready
I think the problem is in this line: var j = $(".pics").index(this); and I think it should be rewritten like this: var j = $(this).index(); It'd be helpful if you could add console.log(j); just after the line in question to see what j ends up being. When this line executes var matched_array_pics = grand_array_pics[j]; I think you're getting undefined because j is not a number when your code runs.

return or send variable to onchange event

I am trying to achieve the same functionality of a function from two separate events. So the function I created is:
function adding_stuff() {
var names = [];
var dates = [];
for(var i = 0; i < this.files.length; i++) {
//adding stuff to names and dates
}
$(".primary .panel-content").append("<ul class='list-unstyled'></ul>");
for(var i in names) {
var li = "<li>";
$(".primary .panel-content ul").append(li.concat(names[i]))
}
}
There are two buttons primary and secondary. I want the same functionality for both the functions but the output in different <div>. Currently the selected <div> is ".primary", however I want this to depend on the button which has been clicked.
The function is triggered using:
$("#primary").onchange = adding_stuff;
$("#secondary").onchange = adding_stuff;
NOTE: primary and secondary are inputs of type file.
You can add additional data when you register the callback, which will be made available within the event handler:
$('#primary').on('change', { target: '.primary' }, adding_stuff);
$('#secondary').on('change', { target: '.secondary' }, adding_stuff);
and then within the handler:
function adding_stuff(ev) {
var cls = ev.data.target; // extract the passed data
...
// file handling code omitted
$(".panel-content", cls).append(...)
}
using jquery's change() event
function adding_stuff(obj,objClass) {
var names = [];
var dates = [];
for(var i = 0; i < obj.files.length; i++) {
//adding stuff to names and dates
}
$("."+ objClass+" .panel-content").append("<ul class='list-unstyled'></ul>");
for(var i in names) {
var li = "<li>";
$("."+ objClass+" .panel-content ul").append(li.concat(names[i]))
}
}
$("#primary").change(function(){
adding_stuff(this,'primary');
});
$("#secondary").change(function(){
adding_stuff(this,'secondary');
});
Try
function adding_stuff(opselector) {
return function() {
var names = [];
var dates = [];
for (var i = 0; i < this.files.length; i++) {
// adding stuff to names and dates
}
var ul = $("<ul class='list-unstyled'></ul>").appendTo(opselector)
for (var i in names) {
ul.append("<li>" + li.concat(names[i]) + "</li>")
}
}
}
$("#primary").change(adding_stuff('.primary .panel-content'));
$("#secondary").change(adding_stuff('.secondary .panel-content'));
You can use $(this).attr("class") inside the function. It will return the class of button who triggered the event.
function adding_stuff() {
var div = $(this).attr("class");
var names = [];
var dates = [];
for(var i = 0; i < this.files.length; i++) {
//adding stuff to names and dates to $div
}
$(div + " .panel-content").append("<ul class='list-unstyled'></ul>");
for(var i in names) {
var li = "<li>";
$(div + " .panel-content ul").append(li.concat(names[i]));
}
}

Categories

Resources