Possible to add a loop while appending to the DOM? - javascript

I'm appending some information to the DOM, but realized that some of the information I need is nested within an object. When I do the below bit of code, the part within the loop returns as undefined. Is there a way to iterate over and pull out this information so that I can append it to my page:
function placeOnPage(allStopsWithRoutes){
allStopsWithRoutes.forEach(function(stop){
$('#stops').append("Stop: " + stop.crossStreets + "<br>" +
// LOOP HERE
stop.routes.forEach(function(route){
"Bus Name: " + busName + "<br>" +
"Stops Away: " + stopsAway + "<br>" +
"Destination: " + destination + "<p>"
});
// END LOOP
);
});
}

I don't think strings can be concatenated that way. Change your approach to concatenate before hand and store it in a variable. Then append the variable
function placeOnPage(allStopsWithRoutes) {
allStopsWithRoutes.forEach(function(stop) {
var concatenatedStr = '';
stop.routes.forEach(function(route) {
concatenatedStr += ("Bus Name: " + busName + "<br>" +
"Stops Away: " + stopsAway + "<br>" +
"Destination: " + destination + "<p>");
});
$('#stops').append("Stop: " + stop.crossStreets + "<br>" + concatenatedStr);
});
}

Related

How do I make the button value an object, not a string?

This is my current code. I want the value of the button to be childData and for it to be the original object, not a string so that I can use it appropriately.
var childData = childSnapshot.val();
document.getElementById("displayChores").innerHTML += (String(childData["clocation"] + " " +
childData["cname"] + " " +
childData["cdescription"] + " " +
childData["ccredits"] + " " +
childData["cexp"]) + "<br />" +
"<button class='chorebtn' value= '"+childData+"' onclick=\"choreDone();\">Mission Complete</button><br>")};
could you just make a the value of the button a JSON.stringify() of the object and then when you want to use it just JSON.parse() it back?

Unable to append, to an html element, values of an array of objects passed as parameter to jQuery each

I have an array of objects, that I loop through using $.each and try and append the array object value to an <li>.
Please find the jQuery below
$(".sidebar").empty().append("<div>"+
"<h5>Student Info</h5>" +
"<ul>" +
$.each(studentInfo, function (index, value) {
console.log(value.studentName + " :studentName ");//prints the student name in the browser console
"<li>Student No " + index + "</li>"
"<li>Name - " + value.studentName + "</li>"
"<li>Contact - " + value.contact + "</li>"
"<li>DOB - " + value.dob + "</li>"
"<li>PAN - " + value.PANNo + "</li>"
"<li>Address - " + value.postalAddress + "</li>"
}) +
"</ul>" +
"</div>")
The above function only prints [object Object],[object Object] in the <li>. I have tried stringifying the array, parsing the array, different ways of appending json objects but its still the same.
The array of objects that I am trying to loop through
var studentInfo = [
{
"studentName":"abc",
"contact":"123456789",
"dob":"22-05-1994",
"PANNo":"ABCDEF1234",
"postalAddress":"chandigarh, sector - 18"
},
{
"studentName":"xyz",
"contact":"123456987",
"dob":"22-05-1994",
"PANNo":"ABCDEF4321",
"postalAddress":"chandigarh, sector - 78"
}
]
I have been at it for hours but unable to figure out what I am doing wrong, I am still new at jQuery and its ways. Any help is really appreciated. Thanks.
jQuery $.each() is not meant to return a string. you use it to treat each object separately. You can't just parse it as string expression.
You will need to split your code into multiple parts.
Part 1: clear .sidebar and prep it for the menu items.
Part 2: build a string items that contain all the object values parsed into HTML list-items.
Part 3: append the string to the '.sidebar'
var studentInfo = [
{
"studentName":"abc",
"contact":"123456789",
"dob":"22-05-1994",
"PANNo":"ABCDEF1234",
"postalAddress":"chandigarh, sector - 18"
},
{
"studentName":"xyz",
"contact":"123456987",
"dob":"22-05-1994",
"PANNo":"ABCDEF4321",
"postalAddress":"chandigarh, sector - 78"
}
];
var items = "";
$.each(studentInfo, function (index, value) {
console.log(value.studentName + " :studentName ");
items += "<li>Student No " + index + "</li>"
+ "<li>Name - " + value.studentName + "</li>"
+ "<li>Contact - " + value.contact + "</li>"
+ "<li>DOB - " + value.dob + "</li>"
+ "<li>PAN - " + value.PANNo + "</li>"
+ "<li>Address - " + value.postalAddress + "</li>"
+ "<hr>" ;
})
+
$(".sidebar").empty().append("<div>"+
"<h5>Student Info</h5>" +
"<ul>" + items + "</ul></div>");
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<div class="sidebar"></div>

Dynamic printing with javascript - building a string with various conditional components

I need to get rid of the comma right after the input firstAuthorInitials.value.slice(0,1) only when it is empty.
In case when in the input firstAuthorInitials.value.slice(0,1) is something written the code works fine.
The code looks like:
if (edition.value == "none") {
div.innerHTML +=
firstAuthorSurname.value + ", " +
firstAuthorName.value.slice(0, 1) + "." +
firstAuthorInitials.value.slice(0,1) + "." + ", " +
year.value +
". <i>" + title.value + "</i>. " +
placeOfPublication.value + ": " +
publisher.value + ".";
}
Create an array, push things into it, then join. Use logic applied to each element to decide if you want to push it or not.
if (edition.value == "none") {
var stringComponents = [];
stringComponents.push(
firstAuthorSurname.value,
", ",
firstAuthorName.value.slice(0, 1),
"."
);
if (/* some kind of logic */) {
stringComponents.push(firstAuthorInitials.value.slice(0,1), "., ");
}
stringComponents.push(
year.value +
". <i>",
title.value,
"</i>. ",
placeOfPublication.value,
": ",
publisher.value,
"."
);
div.innerHTML += stringComponents.join("");
}

XRMService Toolkit not matching parent account guid with another guid stored in a single line text field

I've a hidden field on order form that store guid of parent account of selected contact. Now, in following code snippet I am trying to compare an account guid with that stored in hidden field. But it is returning zero length.
function getOrdersDetail(accountId)
{
var query =
"<a:ColumnSet>" +
"<a:AllColumns>false</a:AllColumns>" +
"<a:Columns xmlns:b='http://schemas.microsoft.com/2003/10/Serialization/Arrays'>" +
"<b:string>createdon</b:string>" +
"</a:Columns>" +
"</a:ColumnSet>" +
"<a:Criteria>" +
"<a:Conditions />" +
"<a:FilterOperator>And</a:FilterOperator>" +
"<a:Filters>" +
"<a:FilterExpression>" +
"<a:Conditions>" +
"<a:ConditionExpression>" +
"<a:AttributeName>new_accountid</a:AttributeName>" +
"<a:Operator>Equal</a:Operator>" +
"<a:Values xmlns:b='http://schemas.microsoft.com/2003/10/Serialization/Arrays'>" +
"<b:anyType i:type='c:string' xmlns:c='http://www.w3.org/2001/XMLSchema'>"+ accountId +"</b:anyType>" +
"</a:Values>" +
"</a:ConditionExpression>" +
"</a:Conditions>" +
"<a:FilterOperator>And</a:FilterOperator>" +
"<a:Filters />" +
"</a:FilterExpression>" +
"</a:Filters>" +
"</a:Criteria>" +
"<a:Distinct>false</a:Distinct>" +
"<a:EntityName>salesorder</a:EntityName>" +
"<a:LinkEntities />" +
"<a:Orders/>" +
"<a:PageInfo>" +
"<a:Count>0</a:Count>" +
"<a:PageNumber>0</a:PageNumber>" +
"<a:PagingCookie i:nil='true' />" +
"<a:ReturnTotalRecordCount>false</a:ReturnTotalRecordCount>" +
"</a:PageInfo>" +
"<a:NoLock>false</a:NoLock>";
var orders = XrmServiceToolkit.Soap.RetrieveMultiple(query);
alert(orders.length);
}

Phonegap - inserting variable into database

I'm trying to insert variables values to a data base but it comes out as 'undefined'.
It is all inside device ready. I'm testing 1st with the variable 'absenceDateFrom'.
var absenceType = document.getElementById('absenceType')
var absenceText = document.getElementById('noteNewAbsence')
var absenceDateFrom = document.getElementById('absenceFrom')
var absenceDateTo = document.getElementById('absenceTo')
db.transaction(
function(tx) {
tx.executeSql("INSERT INTO absences (id,type,absenceFrom,absenceTo,note,aproved,picture) VALUES (" + id++
+ ",'"
+ String(absenceType.value)
+ "','"
+ absenceDateFrom.value.toString
+ "','"
+ absenceDateTo.value.toString
+ "','"
+ "random note (this works but if i put absenceText.value it comes out undefined also"
+ "',"
+ "'true'"
+ ","
+ "'image.jpg'"
+ ")");
}, transaction_error);
I also tried with '?' and [absenceDateFrom] in the end, like I saw on another answer and it still comes out undefined:
var absenceType = document.getElementById('absenceType')
var absenceText = document.getElementById('noteNewAbsence')
var absenceDateFrom = document.getElementById('absenceFrom')
var absenceDateTo = document.getElementById('absenceTo')
db.transaction(
function(tx) {
tx.executeSql("INSERT INTO absences (id,type,absenceFrom,absenceTo,note,aproved,picture) VALUES (" + id++
+ ",'"
+ String(absenceType.value)
+ "',"
+ "?"
+ ",'"
+ absenceDateTo.value.toString
+ "','"
+ "random note (this works but if i put absenceText.value it comes out undefined also"
+ "',"
+ "'true'"
+ ","
+ "'image.jpg'"
+ ")", [absenceDateFrom.value] );
}, transaction_error);
output:
http://prntscr.com/44eb31
Following is the assumptions that I have made about datatypes of the variables.
Number id;
String type,absenceFrom,absenceTo,note,aproved,picture;
Also aproved variable seems to be typo error. Should it not be approved
I have modified your tx() call
If there are any errors in the insert call. check the output of the errorInsert call
db.transaction(
function(tx) {
var sqlStmt = "INSERT INTO absences (id,type,absenceFrom,absenceTo,note,aproved,picture) VALUES ("
+ (id++) + ","
+ "'" + String(type) + "',"
+ "'" + String(absenceDateFrom) + "',"
+ "'" + String(absenceDateTo) + "',"
+ "'" + "random note (this works but if i put absenceText.value it comes out undefined also" + "',"
+ "'" + "true" + "',"
+ "'" + "image.jpg" + "',"
+ ")";
console.log("sqlStmt:"+sqlStmt);
tx.executeSql(sqlStmt,successInsert,errorInsert);
function errorInsert (err) {
console.log("ERROR CODE:"+err.code+":Message:"+err.message);
}
function successInsert(tx, result) {
console.log("SuccessInsert():Last inserted ID = " + result.insertId);
console.log("SuccessInsert():rowsAffected: " + result.rowsAffected);
}
}, transaction_error);
First: try to console.log(absenceDateTo) before inserting and be sure that the value is not undefined.
Second: In the line :
absenceDateTo.value.toString
You are passing the function context but you should call the function instead.
absenceDateTo.value.toString()
Try this ;)

Categories