Trying to crack this little issue I have..
I am using parse.com to store and retrieve data and I have a JSON object I am trying to retrieve a part of to append to an HTML
var tempObject = Parse.Object.extend("Dev");
var query = new Parse.Query(tempObject);
query.notEqualTo("objectId", "Dan Stemkoski");
query.find({
success: function(results) {
alert("Successfully retrieved " + results.length + " receipts");
for (var i = 0; i < results.length; i++) {
var object = results[i];
$("#receipts").html(object.get('receipt_title'));
console.log(object)
//alert(object.id + ' - ' + object.get('receipt_title'));`
The result I want to show in
<div id = receipts>
<div>
Unfortunately for some reason I am getting only one line instead of the 10 that I should be getting.
I know I should loop somehow to get the results but all my tries have failed me so far.
Thanks in advance for help!
You need to add the result to the html, as right now you just replace the previous result with the next one. Instead of
$("#receipts").html(object.get('receipt_title'));
try
var html = $("#receipts").html();
$("#receipts").html(html + object.get('receipt_title'));
Also, just to mention, if you want to be efficient it might be better to just keep adding to a variable and write to the DOM only once. So:
var html = "";
for(/* Do your for loop here, thats all correct*/){
/*Do everything the same apart from the $("#receipts").html() line*/
html += object.get('receipt_title');
}
$("#receipts").html(html);
The less times you modify the DOM, the better.
From the looks of it, you are actually getting only the last line.
Try fixing it like this:
var tempObject = Parse.Object.extend("Dev");
var query = new Parse.Query(tempObject);
query.notEqualTo("objectId", "Dan Stemkoski");
query.find({
success: function(results) {
alert("Successfully retrieved " + results.length + " receipts");
// Clear existing html from #receipts
$("#receipts").html("");
for (var i = 0; i < results.length; i++) {
var object = results[i];
// Adds to html of previous results (empty on first result)
$("#receipts").html($("#receipts").html() + object.get('receipt_title'));
console.log(object)
//alert(object.id + ' - ' + object.get('receipt_title'));
}
}
});
Nice.. I actually managed to solve it a bit differently:
$("#receipts").append(object.get('reciept_title'));
$("#receipts").append("<br>");
I am trying to figure out how to center the results, tried to add HTML after the append function but it broke the code for some reason
You're overwriting the contents of #receipts every time you loop through. Try this (after the first alert):
var datas = new Array();
$.each(results, function(index, data) {
datas.push('<span>'+ data.receipt_title +'</span>');
});
$("#receipts").data(options.join(''));
Play around with it a little until it does what you want it to.
Related
It's my first time working with database using socket.io and I keep running into a problem.
I have a number of objects in my database labeled as "artid,artimg,artimg". Artid has multiple entries that were labeled "Artifact001", "Artifact002", "Artifact003" etc. I'm trying to remove the word "Artifact" from the string leaving only numbers. But when I'm trying to use .replace expression it messes up with the line localStorage.getItems() instead of what's inside 'artid'. Is it possible to edit artid, or would I have to do it directly in the database? Please advise.
socket.on('toClient', function (data) {
for (var i = 0; i <data.DBarray.length ; i++) {
console.log(data.DBarray[i]);
localStorage.setItem(i.toString()+"artid", data.DBarray[i].artid);
//omit other values for now
}
});
$(document).ready(function() {
console.log('localStorage length: ' + (localStorage.length)/8);
for (var i = 0; i < (localStorage.length)/8; i++) {
$("ul").append("<li><h3 class='artifact_id'>"+localStorage.getItem(i.toString()+'artid')+"</h3></li>");
artid = artid.replace(/ *\b\S*?Artifact\S*\b/g, '');
}
In your for...loop try this:
artid = localStorage.getItem(i.toString()+'artid').replace(/ *\b\S*?Artifact\S*\b/g, '');
$("ul").append("<li><h3 class='artifact_id'>"+artid +"</h3></li>");
That should grab the value from localStorage, strip out the artifact and store it into a variable, which you can print onto the page.
Im stuck.
I have a button which returns information about a event, name, date and so on.
In the script it looks like this:
for(var i = 0; i < result.length ; i++)
{
var item = result[i];
$("#eventList").append("<h3>" + result.eventDate + "</h3>" + "<br>" + result.eventId + "<br>" + result.description + "<br>");
}
This generates a list of events that goes to a div, alla of the events in one div. But i would like every event to be placed in one separate div/box.
Any ideas?
You can create them inside a div and then append all of them at the end to the dom.
var divs = [];
var $div;
results.forEach(function(item){
$div = $('<div></div>');
$div.append("<h3>" + item.eventDate + "</h3>");
$div.append("<br>"+ item.eventId);
$div.append("<br>"+ item.description);
divs.push($div);
});
$("#eventList").append(divs);
You can create your item variable inside the for loop. When ii gets too big, result[ii] will be undefined or false, and the loop will stop. I prefer to use ii to i, because it's easier to find if I want to search for a repeat loop.
Each jQuery operation returns the jQuery object that it was applied to, so you can chain your operations. You can create an empty element, and then set its text in the next operation, to make the code more compact.
for(var ii=0, item; item=result[ii]; ii++) {
$("#eventList")
.append($("<div>")
.append($("<h3>").text(item.eventDate))
.append($("<p>").text(item.eventId))
.append($("<p>").text(item.description))
)
}
jsFiddle
I am using the following code to get the answers and questions of json file:
$(document).ready(function () {
$.getJSON("data.json", function (json) {
var anserFor1st = json.questions[0].answers;
var anserFor2nd = json.questions[1].answers; //If it's more than two use a loop
document.getElementById("content").innerHTML = JSON.stringify(anserFor1st) + "<br/>" + JSON.stringify(anserFor2nd);
var aString = "";
Object.keys(anserFor1st).forEach(function (k) {
aString += anserFor1st[k] + "<br/>";
});
Object.keys(anserFor2nd).forEach(function (k) {
aString += anserFor2nd[k] + "<br/>";
});
document.getElementById("content").innerHTML = aString;
});
});
Instead I want to change dynamically the index of the answers&question, aka write the following:
var anser = json.questions[i].answers;
I have to change the index according to event-listener to clicking next and forward buttons in the html file.
How do I change the index dynamically?
I think you mean you want this:
$(document).ready(function () {
$.getJSON("data.json", function (json) {
var answers = [];
var aString = "";
for (var i = 0; i < json.questions.length; i++)
{
answers[i] = json.questions[i].answers;
document.getElementById("content").innerHTML += JSON.stringify(answers[i]) + "<br/>";
for (var j = 0; j < answers[i].length; j++)
{
aString += answers[i][j] + "<br/>";
}
}
document.getElementById("content").innerHTML = aString;
});
});
This code does exactly what yours did, but there are some things in there that make no sense (such as first loading the json.questions[i].answers into the content element, only to then replace it a few lines later with the contents of aString.) You also stringify the JSON before placing it into the DOM, but I'd have expected you to do the opposite (parsing it, since you already just retrieved it as JSON, so stringifying it again shouldn't do anything).
Basically, I'm not entirely sure what you mean by your question, so if I misunderstood please clarify your question.
EDIT: if your problem is just remembering which question you're on, make a variable to hold the number of the current question (e.g. var currentQuestion = 1;), and then just change that based on what button is clicked.
For example:
$("#buttonPrevious").on("click", function (e)
{
currentQuestion--;
});
$("#buttonNext").on("click", function (e)
{
currentQuestion++;
});
Of course you can check for minimum/maximum question numbers (for example, your max number of questions can be equal to the last value of i in the loop above).
Okay I have a a couple of functions. I don't think most of them are relevant. What I want to do is create an html list when you click a button, and store the value in an array. However I want to be able to update this list without outputting the entire array again. I have it set up to accept the input and I can get it to loop and print the array but it will print the entire array and I only want one. This seems like a common thing but my Google-fu returned nothing.
So I have a list variable that connects to an input, logs it into an array, and another function to clear it and print out the values.
Code snippet:
var listItemInput= document.getElementByID("listItem");
var listItem= [];
function insertListItem(){
listItem.push(listItemInput.value);
clearAndShow();
}
function clearAndShow(){
listItemInput.value= "";
}
function printList{
for (var i = 0; i < listItem.length; i++){
document.getElementById("list").innerHTML += '<li>' + listItem[i] + '</li>';
}
When the printList funciton is called by pressing the button it prints the entire array over however I would like a button that simply prints the newest item. How could I do that?
For clarification, I need to print out the list to html and store the values in an array, the values will later be referenced in an if else argument to combine and print them with new variables.
EDIT:
I plugged in the var = lastIndex and changed it as well as made two more variables for my list. This seems to make it work. Thank you.
You could keep track of the last index printed.
var listItemInput= document.getElementByID("listItem");
var listItem = [];
var lastIndex = 0; //Keep track of the last index shown.
function insertListItem() {
listItem.push(listItemInput.value);
clearAndShow();
}
function clearAndShow() {
listItemInput.value = "";
}
function printList() {
for (; lastIndex < listItem.length; lastIndex++) {
document.getElementById("list").innerHTML += '<li>' + listItem[lastIndex] + '</li>';
}
}
This approach assumes you won't be removing items from listItem array, which you didn't express is something that would be done.
If you only want one element, why do you need to iterate?
function printList() {
document.getElementById('list').innerHTML = '<li>' + listItem[listItem.length-1] + '</li>';
}
I'm having some trouble getting my code to work. This is what I have so far.
function outputNamesAndTotal() {
var name;
var outputTable;
var inputForm;
var nameArray;
var outputDiv;
outputDiv = document.getElementById("outputDiv");
inputForm = document.getElementById("inputForm");
outputTable = document.getElementById("outputTable");
name = inputForm.name.value;
nameArray = [];
nameArray.push(name);
for (var i = 0; i > nameArray.length; i++) {
outputTable.innerHTML += "<tr>" + nameArray[i] + "</tr>";
}
inputForm.name.focus();
inputForm.name.select();
return false;
}
When I add the loop it breaks the code completely, but I can't figure out why.
What I'm trying to do is use an HTML form to get a name from the user. Once the user enters the name, the program adds the name to the array, and outputs each array entry to a row in a table.
It's pretty basic, but it's still giving me all kinds of trouble!
I think you are clearing your array of names every time you call the function. You should bring the line:
nameArray = [];
out and make it global.
I ran a quick test and the following code works in at least FireFox
Edited to use appendChild
<html>
<head>
<script type='text/javascript'>
var names = [];
function addName() {
var nameTxt = document.getElementById('name_txt');
var name = nameTxt.value;
names.push(name);
var outTable = document.getElementById('out_tbl');
var row = document.createElement('tr');
var entry = document.createElement('td');
var txt = document.createTextNode(name);
entry.appendChild(txt);
row.appendChild(entry);
outTable.appendChild(row);
var numDiv = document.getElementById('num_div');
removeAllChildren(numDiv);
var numTxt = document.createTextNode('You have ' + names.length + ' names');
numDiv.appendChild(numTxt);
}
function removeAllChildren(e) {
while (e.hasChildNodes()) {
e.removeChild(e.firstChild);
}
}
</script>
</head>
<body>
<table id='out_tbl'>
</table>
<div id='num_div'>You have 0 names</div>
<input id='name_txt' type='text'/>
<button onclick="addName()">CLICK</button>
</body>
</html>
Edit: Oh yeah and you are the fact that you are looping through the array every time. If you "globalize" the name array, you're gonna print the whole array every time you add a name.
Edit x2: the code you originally posted had nameArray as a local variable inside the function. This effectively clears the array every time you call the function. Then every time you call the function you add the current name to the now empty array, and loop through all 1 (one) elements that the array now holds.
What you want to do is "globalize" the name array, and remove the loop from your function. This will allow you to build up your name array across multiple calls, and works the way that you want it.
Also, innerHTML is not really the best way to add things to the page. I would suggest using appendChild().
-C
for (var i = 0; i > nameArray.length; i++) {
I think you mean i < nameArray.length