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

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("");
}

Related

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>

Get value from the previous loop using JavaScript

I would need to keep the value from the loop where authorId = 1 and then print it out as another value in the next loop (authorId = 3). I mean that I need to keep authorSurname.value (id = 1) and print it in the loop (authorId = 3) as the secondAuthor.value because in the loop (authorId = 3) the string authorSurname takes another value. Can you tell me how can I fix it?
if(authorId === 0) {
div.innerHTML = firstAuthorSurname.value + year.value + page.value + pageOtherValue;
}
else if (authorId === 1) {
div.innerHTML = firstAuthorSurname.value + " i " + authorSurname.value + " (" + year.value + ");
var secondAuthorSurname = authorSurname.value;
}
else if (authorId === 2) {
return secondAuthorSurname;
div.innerHTML = firstAuthorSurname.value + ", " + secondAuthorSurname.value + " and " + authorSurname.value + " (" + year.value + ") " + firstAuthorSurname.value + ", " + secondAuthorSurname.value + " and " + authorSurname.value + ", " + year.value + ")" + firstAuthorSurname.value + ", " + secondAuthorSurname.value + " and " + authorSurname.value + ", " + year.value + ") showed that... ";
}
Your code does not contain a loop but if you would like to save a value to use outside of a for loop declare the variable outside the loop and then you will have access to it outside the loop.
text = "";
cars = ["honda", "chevy"];
for (i = 0; i < cars.length; i++) {
text += cars[i];
}
console.log(text);
>>hondachevy
If you are trying to save a value to be used in a different condition in the if statement inside a for loop you can follow the same pattern
text = "";
for (i = 0; i < 4; i++) {
if(i === 0){
text += "to be used when i is 1";
}
else if(i === 1){
console.log(text);
text += " hello";
}
}
console.log(text);
output
>>to be used when i is 1
>>to be used when i is 1 hello
Also why don't you use a switch statement instead of a long if else. See the link below for how to do switch statements in javascript.
http://www.w3schools.com/js/js_switch.asp

Possible to add a loop while appending to the DOM?

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);
});
}

javascript adding multiple variables to mailto body with a for loop

This function below is supposed to add some of the variables "mess" into the body of an email message. The "who" and "what" gets read in the email address and subject ok, and the first line of the mess variables "ISBN" gets read into the body as it should...but the rest of the mess variables that should be read into the body does not get entered. Wondering if the for loop is not looping correctly. Just trying to narrow the problem down. Any help would very nice.
function mailOrder()
{
who=document.order.Email.value;
what="order";
var mess = "";
for (var n = 0; n < bookDB.length; n++)
{
bookNum = bookDB[n].quantity;
if (bookNum > 0)
{
mess += "ISBN: " + bookDB[n].number + " ";
mess += "Book Name: " + bookDB[n].title + " ";
mess += "Quantity Ordered: " + bookDB[n].quantity + " ";
mess += "Book Price: " + bookDB[n].price + " ";
mess += " ***************************************************** ";
}
}
mess +="Customer Name: " + document.order.Name.value + " ";
mess +="Email Address: " + document.order.Email.value + " ";
mess +="Address: " + document.order.Address.value + " ";
mess +="City: " + document.order.City.value + " ";
mess +="Country: " + document.order.Country.value + " ";
parent.location.href='mailto:'+who+'?subject='+what+'&body='+mess;
}

Function in JavaScript that outputs concat url to YUI Chart Library Output

Trying to properly write a function in JavaScript that outputs a concat'd url to Chart Library Output (for chart re-rendering)... based on selected options in dropdown list.
Problem: I am not getting the chart to re-render with the concatenated url (which should be sent each time an option is selected in the dropdown).
JavaScript code in head:
function httpGet(theUrl)
{
var xmlHttp = null;
xmlHttp = new XMLHttpRequest(); // instantiate request
xmlHttp.open( "GET", theUrl, false ); // open url
xmlHttp.send( null ); // sending nothing
return xmlHttp.responseText; // return url's data as text
};
function selectFabric(){
var urlString = "http://localhost:8083/tbl/sparqlmotion?id=LiabilityChart&arg1=";
var fabrics = document.getElementById('fabrics');
var selectedFabric = fabrics.options[fabrics.selectedIndex];
var linkAddTogether = [urlString + selectedFabric.value];
var linkResult = linkAddTogether[0];
var result = httpGet(linkResult);
if (selectedFabric.value != "nothing"){
return linkResult; // update begins // document.write(linkAddTogether)
};
};
function revive (key, value) {
if (value.datatype == "http://www.w3.org/2001/XMLSchema#double" || // if datatype is this
value.datatype == "http://www.w3.org/2001/XMLSchema#integer" || // or, this
value.datatype == "http://www.w3.org/2001/XMLSchema#float") // or, this
{
return (parseInt(value.value)) // if '#double', '#integer', or '#schema', then: 'vars' label + convert the datatype's float value to integer
}
else if (value.type == 'literal')
{
return (value.value) // if datatype's value is a literal: 'vars' label + return as a string
}
else if (value.datatype == 'http://www.w3.org/2001/XMLSchema#date')
{
return value.value // if "XMLSchema#date's" value is a literal: 'vars' label + return as a string
}
else
{
return value // if datatype is anything else: 'vars' label + return value as a string
}
};
var scriptHead = ["YUI().use('charts',function(Y){var myDataValues=\n\n["];
var scriptTail = ["\n];\n\nvar styleDef={series:{Stock:{line:{color:'#EEB647'},marker:{fill:{color:'#eee',alpha:0,wmode:'transparent'},border:{color:'#222',alpha:0,wmode:'transparent'},over:{fill:{color:'#eee'},border:{color:'#000'},width:9,height:9}}},Liability:{line:{color:'#171944'},marker:{fill:{color:'#eee',alpha:0,wmode:'transparent'},border:{color:'#222',alpha:0,wmode:'transparent'},over:{fill:{color:'#eee'},border:{color:'#000'},width:9,height:9}}},Shipment:{line:{color:'#ff0000',alpha:0,wmode:'transparent'},marker:{fill:{color:'#eee',alpha:0,wmode:'transparent'},border:{color:'#ff0000',alpha:0,wmode:'transparent'},over:{fill:{color:'#ff0000',alpha:0,wmode:'transparent'},border:{color:'#000',alpha:0,wmode:'transparent'},width:16,height:16}}},Production:{line:{color:'#FFD700',alpha:0,wmode:'transparent'},marker:{fill:{color:'#eee',alpha:0,wmode:'transparent'},border:{color:'#FFD700',alpha:0,wmode:'transparent'},over:{fill:{color:'#FFD700',alpha:0,wmode:'transparent'},border:{color:'#000',alpha:0,wmode:'transparent'},width:16,height:16}}},Order:{line:{color:'#006400',alpha:0,wmode:'transparent'},marker:{fill:{color:'#eee',alpha:0,wmode:'transparent'},border:{color:'#006400',alpha:0,wmode:'transparent'},over:{fill:{color:'#006400',alpha:0,wmode:'transparent'},border:{color:'#000',alpha:0,wmode:'transparent'},width:16,height:16}}}}};var myAxes={dateRange:{keys:['date'],position:'bottom',type:'category',title:'Date Range',styles:{majorTicks:{display:'none'},label:{rotation:-45,margin:{top:5}},title:{fontSize:'90%'}}}};var mychart=new Y.Chart({dataProvider:myDataValues,interactionType:'planar',render:'#mychart',categoryKey:'Date',styles:styleDef,categoryType:'time',horizontalGridlines:{styles:{line:{color:'#fff'}}},verticalGridlines:{styles:{line:{color:'#fff'}}}})});\n\n"];
var simpleHead = [scriptHead];
var simpleTail = [scriptTail];
var oldData = JSON.parse(result, revive);
HTML code for form (in body):
form style="width:200px; color:#333; padding-right:5px; padding-bottom:2px; padding-left:55px; margin-top:0px; clear:none;" name="properties" id="properties">
select style="width:160px; color:#333; clear:none; display:block;" name="fabrics" id="fabrics" onChange="selectFabric()">
option value="nothing">Select Fabric END option
option value="KOD23-4074-LV">KOD23-4074-LV END option
option value="SGOD2-2858-LV">SGOD2-2858-LV END option
option value="W-897-LV">W-897-LV END option
option value="FF-4084-LV">FF-4084-LV END option
END select
END form
JavaScript code for chart (write script in body to render YUI chart plug-in):
document.write('\x3Cscript type="text/javascript" id="source">');
document.write(simpleHead[0] + '\n{Date: "' + oldData.results.bindings[0].date + '", Liability: ' + oldData.results.bindings[0].liability + ", Stock: " + oldData.results.bindings[0].stock + ", " + oldData.results.bindings[0].event + ": " + oldData.results.bindings[0].current + "}," + "\n\n");
document.write('\n{Date: "' + oldData.results.bindings[1].date + '", Liability: ' + oldData.results.bindings[1].liability + ", Stock: " + oldData.results.bindings[1].stock + ", " + oldData.results.bindings[1].event + ": " + oldData.results.bindings[1].current + "}," + "\n\n");
document.write('\n{Date: "' + oldData.results.bindings[2].date + '", Liability: ' + oldData.results.bindings[2].liability + ", Stock: " + oldData.results.bindings[2].stock + ", " + oldData.results.bindings[2].event + ": " + oldData.results.bindings[2].current + "}," + "\n\n");
document.write('\n{Date: "' + oldData.results.bindings[3].date + '", Liability: ' + oldData.results.bindings[3].liability + ", Stock: " + oldData.results.bindings[3].stock + ", " + oldData.results.bindings[3].event + ": " + oldData.results.bindings[3].current + "}," + "\n\n");
document.write('\n{Date: "' + oldData.results.bindings[4].date + '", Liability: ' + oldData.results.bindings[4].liability + ", Stock: " + oldData.results.bindings[4].stock + ", " + oldData.results.bindings[4].event + ": " + oldData.results.bindings[4].current + "}," + "\n\n");
document.write('\n{Date: "' + oldData.results.bindings[5].date + '", Liability: ' + oldData.results.bindings[5].liability + ", Stock: " + oldData.results.bindings[5].stock + ", " + oldData.results.bindings[5].event + ": " + oldData.results.bindings[5].current + "}," + "\n\n");
document.write('\n{Date: "' + oldData.results.bindings[6].date + '", Liability: ' + oldData.results.bindings[6].liability + ", Stock: " + oldData.results.bindings[6].stock + ", " + oldData.results.bindings[6].event + ": " + oldData.results.bindings[6].current + "}" + simpleTail[0] + "\n\n");
document.write('\x3C/script>');

Categories