What am I doing wrong? - javascript

This is my Javascript code I have so far. I am trying to create a personInfo() object with 2 functions. I am not sure what I am doing wrong.
var personInfo =
{
personInfo.personRelation: " ",
personInfo.personName: " ",
personInfo.personAge: 0,
personInfo.personGender: " "
var relationValue = personRelation;
var nameValue = personName;
var ageValue = personAge;
var genderValue = personGender;
getPersonInfo: function()
{
document.write( "<p>" + personInfo.personRelation + "<br />" );
document.write( "Name: " + personInfo.personName + "<br />");
document.write( "Age: " + personInfo.personAge + "<br />" );
document.write( "Gender: " + personInfo.personGender + "</p>" );
}
setPersonInfo(relationValue, nameValue, ageValue, genderValue): function()
{
this.relationValue = relationValue;
this.nameValue = nameValue;
this.ageValue = ageValue;
this.genderValue = genderValue;
}
}; // end object personInfo
This my html code...I am trying to print each object with the while loop. I am very new to Javascript, so I am not sure if I mistakes in the external javascript file or if it is simply my implementation. Any help would be great. Thank you.
<html>
<head>
<link rel="stylesheet" href="object.css" type ="text/css" />
<title>Object Test</title>
<script type="text/javascript" src="MyObject.js">
var people = new Array(5);
</script>
</head>
<body>
<script type="text/javascript" src="MyObject.js">
var dad_info = setPersonInfo("Dad", "Kenneth Vavrock", 66, "Male");
dad_info = people[0];
var mom_info = setPersonInfo("Mom", "Connie Vavrock", 63, "Female");
mom_info = people[1];
var brother_info = setPersonInfo("Brother", "Craig Vavrock", 33, "Male");
brother_info = people[2];
var nephew_info = setPersonInfo("Nephew", "Sawyer Vavrock", 1, "Male");
nephew_info = people[3];
var dad_info = setPersonInfo("Step Mother", "Bonnie Vavrock", 70, "Female");
stepmother_info = people[4];
var count = 1;
while ( count >= 0 )
{
dad_info.getPersonInfo();
mom_info.getPersonInfo();
brother_info.getPersonInfo();
nephew_info.getPersonInfo();
stepmother_info.getPersonInfo();
count--;
}
</script>
</body>
</html>

Your "personInfo" object is malformed, it looks like a mix between a object literal and a class-like function. Have a look at this tutorial
Also, do not use an empty string " " as default value for anything (unless you really need to), there is really no point to it.
To solve the problem at hand.
var personInfo = function () {
this.personRelation = "";
this.personName = "";
this.personAge = 0;
this.personGender = "";
this.getPersonInfo = function () {
document.write( "<p>" + personInfo.personRelation + "<br />" );
document.write( "Name: " + personInfo.personName + "<br />");
document.write( "Age: " + personInfo.personAge + "<br />" );
document.write( "Gender: " + personInfo.personGender + "</p>" );
}
};
This way it can be used as such:
var people = []; // Create an empty array
// Create new person info for "dad"
var dad_info = new personInfo();
dad_info.personRelation = "...";
// [...]
people.push(dad_info); // Add dad_info to the array.
You should be all set.

Related

How to display the data in table format which im currently displaying in page via js ?( i already got input from previous page)

want to display my data in table format in javascript
able to display the data which i recieved from my previous page through query string in next page through document.write
<!DOCTYPE html>
<html>
<head>
<title> result </title>
</head>
<body>
<script>
function getParams(){
var idx = document.URL.indexOf('?');
var params = new Array();
if (idx != -1) {
var pairs =
document.URL.substring(idx+1,document.URL.length).split('&');
for (var i=0; i<pairs.length; i++){
nameVal = pairs[i].split('=');
params[nameVal[0]] = nameVal[1];
}
}
return params;
}
params = getParams();
firstname = unescape(params["firstname"]);
lastname = unescape(params["lastname"]);
age = unescape(params["age"]);
email = unescape(params["email"]);
mobile = unescape(params["mobile"]);
document.write( "firstname = " + firstname + " <br>" );
document.write( "lastname = " + lastname + "<br>" );
document.write( "age = " + age + "<br>" );
document.write( "email-id = " + email + "<br>" );
document.write( "mobile = " + mobile + "<br>");
</body>
display my data inside table

How to get this data using the loop?

How do i show all the data by using the loop to display all the data from json to html ?
ATM , I am able to print one of the data. but if i am using data[i] the code will not display any data.
I think I mess up the the concept of object and array.
please advice me , how to loop thru object , like array?
thanks
var getWeather = document.getElementById('weather');
var requestWeather = new XMLHttpRequest();
//+'-31' +'&lon='+'150'
requestWeather.open('GET','https://fcc-weather-api.glitch.me/api/current?lat=-31&lon=150');
requestWeather.onload = function () {
var weatherData = JSON.parse(requestWeather.responseText);
console.log(weatherData);
getHTML(weatherData);
};
requestWeather.send();
function getHTML(data) {
var weatherString = "";
for(var i in data.weather ){
var x= data.weather[i].main;
weatherString+= "<p class='weather'>" + x + "</p>";
// weatherString+= "<p>" + data.currently.summary + "</p>";
// console.log(data[i].city);
}
getWeather.insertAdjacentHTML("beforeend", weatherString);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="weather"></div>
to get all data check for object and do recursive loop
var getWeather = document.getElementById('weather');
var requestWeather = new XMLHttpRequest();
//+'-31' +'&lon='+'150'
requestWeather.open('GET', 'https://fcc-weather-api.glitch.me/api/current?lat=-31&lon=150');
requestWeather.onload = function() {
var weatherData = JSON.parse(requestWeather.responseText);
//console.log(weatherData);
getHTML(weatherData);
};
requestWeather.send();
function getHTML(data) {
var weatherString = "";
for(var i in data) {
var x = data[i];
if(typeof(x) == "object") {
getHTML(x);
}
else {
weatherString += "<p class='weather'><b>" + i + "</b>: " + x + "</p>";
// weatherString+= "<p>" + data.currently.summary + "</p>";
// console.log(data[i].city);
}
}
getWeather.insertAdjacentHTML("beforeend", weatherString);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="weather"></div>
var getWeather = document.getElementById('weather');
var requestWeather = new XMLHttpRequest();
//+'-31' +'&lon='+'150'
requestWeather.open('GET', 'https://fcc-weather-api.glitch.me/api/current?lat=-31&lon=150');
requestWeather.onload = function() {
var weatherData = JSON.parse(requestWeather.responseText);
getHTML(weatherData);
};
requestWeather.send();
function getHTML(data) {
var weatherString = "";
for (var i in data.weather) {
var x = data.weather[i].main;
weatherString += "<p class='weather'>" + x + "</p>";
$.each(data.main, function(i, f) {
var main = "<div>" + i + ": " + f + "</div>";
$(main).appendTo("#main");
});
}
getWeather.insertAdjacentHTML("beforeend", weatherString);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="weather"></div>
<div id="main"></div>
use foreach loop to iterate over all object
read more from here

JavaScript: Remove Double Quotes - JSON.Stringify()

After using he JSON.stringify() method in JavaScript to allow JSON data render in the browser it outputs double quotations " " at either end of the property rendered in the browser - any idea how to resolve this?
Here is my code -
<li class="divider">Brown Eyes</li>
<div id="output1"></div>
<li class="divider">Green Eyes</li>
<div id="output2"></div>
<script>
var myContainer = "";
var a = new XMLHttpRequest();
a.open("GET", "https://api.myjson.com/bins/1dwnm", true);
a.onreadystatechange = function () {
console.log(a);
if (a.readyState == 4) {
var obj = JSON.parse(a.responseText);
for (i = 0; i < obj.length; i++) {
if (obj[i].eyeColor == 'brown') {
var myContainer = "<ul class='list'><li>" + obj[i].name.first + " " + obj[i].name.last + " - " + obj[i].eyeColor + "</li></ul>";
var myContainer = JSON.stringify(myContainer);
document.getElementById('output1').innerHTML += myContainer;
}
if (obj[i].eyeColor == 'green') {
var myContainer = "<ul class='list'><li>" + obj[i].name.first + " " + obj[i].name.last + " - " + obj[i].eyeColor + "</li></ul>";
var myContainer = JSON.stringify(myContainer);
document.getElementById('output2').innerHTML += myContainer;
}
}
}
}
a.send();
</script>
Because "<ul class='list'><li>Faye Garrett - brown</li></ul>" is not a valid JSON string.
Uncomment your stringify lines and it works.

getting undefined value:app script

Here, i am trying to send a mail to replyEmail specified below. But it is giving as undefined value. Why its happening even though i am giving correct email id in google form? Some times its coming correct. But for another time its giving as undefined value.
function sendEmail(e) {
/**
var email = e.values[1];
var item = e.values[2];
var cost = e.values[3];
*/
var serviceInformation = e.values[1],
language = e.values[2],
meetingType = e.values[3],
eventDate = e.values[4],
clientName = e.values[5],
detailedDirections = e.values[6],
onSitePOCName = e.values[7],
onSitePOCNumber = e.values[8],
department = e.values[9],
contactPhoneNumber = e.values[10],
approval = e.values[11]; //the one we need to modif,
requestorEmail = e.values[12],
managerEmail = e.values[13],
Language2 = e.values[14],
interpreterName = e.values[15],
interpreterAgency = e.values[16],
dateConformationSent = e.values[17],
specialNotes = e.values[18];
var url = 'https://script.google.com/a/macros/richmond.k12.va.us/s/AKfycbwuRr1boKTH0v1mprWmc7PE66_mQ_dmPE0lyWb7vkfiyW3pn31b/exec';
// might be that the & needs to be a ?
var approve = url + '?approval=true' + '?reply=' + requestorEmail;
var reject = url + '?approval=false' + '?reply=' + requestorEmail;
var html = "<HTML><body>"+
"<h2>please review</h2><br />"
+"<P>" + language +" " + serviceInformation
+"<p>" + meetingType+ " on "+ eventDate + " for " +clientName
+"<p>" + "Location: "+ department
+"<p>" + "requester: "+ requestorEmail+ " "+
"<p>"+
"Approve<br />"+
"<p>"+
"Reject<br />"+
"</HTML></body>";
var html = [
"<html>",
"<body>",
"<h2>please review</h2> <br/>",
"<p>" + language +" " + serviceInformation,
"<p>" + meetingType + " on " + eventDate + " for " + clientName,
"<p>Location: " + department,
"<p>Requester: " + requestorEmail,
"<p>Approve<br/>",
"<p>Reject<br />",
"</body>",
"</html>";
].join('');
MailApp.sendEmail(managerEmail, "Approval Request", "what no html?", {
htmlBody: html
});
}
function doGet(e) {
var app = UiApp.createApplication(),
aprovalResponce = (e.parameter.approval == 'true') ? 'Approved.' : 'Sorry, you need to reschedule',
msg = "Your manager said :" + aprovalResponce;
var replyEmail = e.parameter.reply; // !!!
Logger.log(replyEmail);
MailApp.sendEmail(replyEmail, "Approval Request", msg);
var helloWorldLabel = app.createLabel(msg);
app.add(helloWorldLabel);
return app;
}
Its because space is not accepted while parsing the data in google script.It should be encoded and then the data is to be send.It can be encoded using encodeURIcomponent().

Parsing a JSON Array with JavaScript returning selected parts

I have a very simple snipplet for a json array and a javascript function that now returns a single argument:
<!DOCTYPE html>
<html>
<body>
<h2>JSON Array Test</h2>
<p id="outputid"></p>
<script>
var arrayinput = '{"collection":[' +
'{"firstAttr":"XXXA","secAttr":"13156161","lastAttr":"01" },' +
'{"firstAttr":"XXXB","secAttr":"11153325","lastAttr":"02" },' +
'{"firstAttr":"XXXC","secAttr":"14431513","lastAttr":"03" },' +
'{"firstAttr":"XXXC","secAttr":"161714","lastAttr":"01" },' +
'{"firstAttr":"XXXC","secAttr":"151415","lastAttr":"02" },' +
'{"firstAttr":"XXXC","secAttr":"114516","lastAttr":"02" },' +
'{"firstAttr":"XXXC","secAttr":"131417","lastAttr":"03" },' +
'{"firstAttr":"XXXC","secAttr":"1311865","lastAttr":"03" },' +
'{"firstAttr":"XXXC","secAttr":"1314153","lastAttr":"01" },' +
'{"firstAttr":"XXXC","secAttr":"13312163","lastAttr":"01" }]}';
obj = JSON.parse(arrayinput);
document.getElementById("outputid").innerHTML =
obj.collection[1].firstAttr + " " + obj.collection[1].secAttr;
</script>
</body>
</html>
Now the problem is that I don't want to return just one value but multiple ones. For example all entrys with lastAttr=01 should be returned.
Therefore I would need something along the line of:
for(var i in obj) {
if(lastAttr[i]="01") {
document.getElementById("outputid").innerHTML =
obj.collection[i].firstAttr + " " + obj.collection[i].secAttr;
} else {
}
}
Any idea on how to make this work?
If you want to perform a where you need to use Array.prototype.filter:
var filteredArr = arr.collection.filter(function(item) {
return item.lastAttr == "01";
});
And, finally, you can use Array.prototype.forEach to iterate results and perform some action:
var outputElement = document.getElementById("outputid");
filteredArr.forEach(function(item) {
// Check that I used insertAdyacentHtml to be sure that all items
// will be in the UI!
outputElement.insertAdjacentHTML("afterbegin", item.firstAttr + " " + item.secAttr);
});
Also, you can do it fluently:
var arr = {
collection: [{
firstAttr: "hello",
secAttr: "world",
lastAttr: "01"
}, {
firstAttr: "hello 2",
secAttr: "world 2",
lastAttr: "01"
}]
};
var outputElement = document.getElementById("outputid");
var filteredArr = arr.collection.filter(function(item) {
return item.lastAttr == "01";
}).forEach(function(item) {
outputElement.insertAdjacentHTML("afterbegin", item.firstAttr + " " + item.secAttr);
});
<div id="outputid"></div>
You need to iterate over the collection Array and append the new stuff. Right now you're iterating the outer object and overwriting the .innerHTML each time.
var out = document.getElementById("outputid");
for (var i = 0; i < obj.collection.length; i++) {
if(obj.collection[i].lastAttr=="01") {
out.insertAdjacentHTML("beforeend", obj.collection[i].firstAttr + " " + obj.collection[i].secAttr);
}
}
Note that I used == instead of = for the comparison, and .insertAdjacentHTML instead of .innerHTML.
if you want to replace html try this
(someCollection) array;
var r = new Array();
var j = -1;
r[++j] = '<ul class="list-group">';
for (var i in array) {
var d = array[i];
if (d.attribute== somevalue) {
r[++j] = '<li class="list-group-item">'
r[++j]=d.otherattribute;
r[++j] = '</li>';
}
}
r[++j] = '</ul>';
//for(var b in r) //alert to see the entire html code
//{ alert(r[b]);}
firstLoadOnPage = false;
var list = document.getElementById('SymptomSection');
list.innerHTML = r.join('');
this replaces the inside of element with classname "SymptomSection"

Categories