Javascript producing random arrays with random numbers in it? - javascript

I am doing a simple assignment for class, and am trying to create a table using just Javascript. I have my table perfectly set up, it's just that every other row it shows a random number, and then skips to the next. how can I get rid of the random row?
var table = ["Name", "Turn Average", "Surface Area", "100% Boosting"];
var names = ["Octane", "Dominus", "Breakout", "X-Devil", "Batmobile"];
var turnaverages = [2.18, 2.22, 2.22, 2.21, 2.25];
var surfacearea = [34495, 34529, 32679, 34242, 34365];
var maxboost = [1.967, 2.031, 2.035, 2.014, 2.10];
function info() {
document.write("<table>");
document.write("<tr>");
//these next lines output the table heading (th) tags for the table (this information doesn't repeat in the table)
document.write("<th>Name</th>");
document.write("<th>Turn Average</th>");
document.write("<th>Surface Area</th>");
document.write("<th>100% Boosting</th>");
document.write("</tr>"); //close first table row element
//create a for loop that will last for the number of days in the forecast
for(var i = 0; i < names.length; i++){
document.write("<tr>"); //create a table row
//output each table data tag for the table with information pulled
from the arrays
document.write("<td>" + names[i] + "</td>");
document.write("<td>" + turnaverages[i] + "</td>");
document.write("<td>" + surfacearea[i] + "</td>");
document.write("<td>" + maxboost[i] + "</td>");
document.write("</tr>");
//depending on the description of the weather for the day, change
the image to be representative to that description -- (for
example on a rainy day, show the rainy image)
if ( names[i] === "Dominus" ) {
document.write("<td>" + turnaverages[i] + surfacearea[i] +
maxboost[i] + "</td>");
}
else if ( names[i] === "Breakout" ){
document.write("<td>" + turnaverages[i] + surfacearea[i] +
maxboost[i] + "</td>");
}
else if ( names[i] === "X-Devil" ){
document.write("<td>" + turnaverages[i] + surfacearea[i] +
maxboost[i] + "</td>");
}
else if( names[i] === "Batmobile" ){
document.write("<td>" + turnaverages[i] + surfacearea[i] +
maxboost[i] + "</td>");
}
document.write("</tr>"); //close the table row element
}
document.write("</table>"); //close the table element
}

You have
document.write("<td>" + maxboost[i] + "</td>");
document.write("</tr>");
followed immediately by weather tests that attempt to write tds, followed again by another
document.write("</tr>"); //close the table row element
So, you just need to delete the first </tr>, since you don't actually want to close the row yet:
var table = ["Name", "Turn Average", "Surface Area", "100% Boosting"];
var names = ["Octane", "Dominus", "Breakout", "X-Devil", "Batmobile"];
var turnaverages = [2.18, 2.22, 2.22, 2.21, 2.25];
var surfacearea = [34495, 34529, 32679, 34242, 34365];
var maxboost = [1.967, 2.031, 2.035, 2.014, 2.10];
function info() {
document.write("<table>");
document.write("<tr>");
//these next lines output the table heading (th) tags for the table (this
document.write("<th>Name</th>");
document.write("<th>Turn Average</th>");
document.write("<th>Surface Area</th>");
document.write("<th>100% Boosting</th>");
document.write("</tr>"); //close first table row element
//create a for loop that will last for the number of days in the forecast
for (var i = 0; i < names.length; i++) {
document.write("<tr>"); //create a table row
//output each table data tag for the table with information pulled
document.write("<td>" + names[i] + "</td>");
document.write("<td>" + turnaverages[i] + "</td>");
document.write("<td>" + surfacearea[i] + "</td>");
document.write("<td>" + maxboost[i] + "</td>");
//depending on the description of the weather for the day, change
if (names[i] === "Dominus") {
document.write("<td>" + turnaverages[i] + surfacearea[i] +
maxboost[i] + "</td>");
} else if (names[i] === "Breakout") {
document.write("<td>" + turnaverages[i] + surfacearea[i] +
maxboost[i] + "</td>");
} else if (names[i] === "X-Devil") {
document.write("<td>" + turnaverages[i] + surfacearea[i] +
maxboost[i] + "</td>");
} else if (names[i] === "Batmobile") {
document.write("<td>" + turnaverages[i] + surfacearea[i] +
maxboost[i] + "</td>");
}
document.write("</tr>"); //close the table row element
}
document.write("</table>"); //close the table element
}
info();
The 2.22345292.031 and similar numbers are a result of string cocatenation - when you take a string and + to it, you will end up with another string. (not sure what you actually want there instead)

Related

Getting values from an api call

Hi all i have a url with returns values (https://api.sunrise-sunset.org/json?lat=35.857368&lng=14.477653). I would like to get the values of sunset and sunrise. The code I am trying is the following but for some reason nothing is happening. Seems that I cannot access 'second level'
$.getJSON('https://api.sunrise-sunset.org/json?lat=35.857368&lng=14.477653', function (data) {
var tr;
for (var i = 0; i < data.length; i++) {
tr = $('<tr/>');
tr.append("<td>" + data[i].results[0].sunrise + "</td>");
tr.append("<td>" + data[i].sunset + "</td>");
$('table').append(tr);
}});
Can someone please help me? thanks
Neither the response object nor .results is an array - remove the array indicies.
const tr = $('tr');
$.getJSON('https://api.sunrise-sunset.org/json?lat=35.857368&lng=14.477653', function (data) {
console.log(data.results.sunrise + ' :: ' + data.results.sunset);
tr.append("<td>" + data.results.sunrise + "</td>");
tr.append("<td>" + data.results.sunset + "</td>");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table><tr></tr></table>

How to sum Total JSON Results?

i have this script to take data from JSON Results, also this script filter results by ID
$(document).ready(function () {
//Call EmpDetails jsonResult Method
$.getJSON("/smetkis/getTrosokList",
function (json) {
var tr;
for (var i = 0; i < json.length; i++) {
if (json[i].skID == '#Html.DisplayFor(model => model.smID)') {
tr = $('<tr />');
tr.append("<td >" + json[i].Artikal + "</td>");
tr.append("<td>" + json[i].kol + "</td>");
tr.append("<td>" + json[i].cena + "</td>");
tr.append($('<td class="vkupno1">' + json[i].vkupnot + '</td>'));
$('table').append(tr);
}
}
});
});
Also i have this script sor SUM Of column with class vkupno1, but not understand the results from cell.
$(document).ready(function () {
colSum();
});
function colSum() {
var sum = 0;
$(".vkupno1").each(function () {
sum += parseFloat($(this).text());
});
$('#result').html((sum).toFixed(2).replace(/(\d)(?=(\d{6})+(?!\d))/g, "$1.") + " €");
}
How to sum (json[i].vkupnot)-value or cell classed "vkupno1"
here is JSON Results:
[{"smetki":null,"trId":1,"skID":1,"Artikal":"gdfgsdgfdg","kol":4.00,"cena":4.00,"vkupnot":16.00},{"smetki":null,"trId":4,"skID":4,"Artikal":"kjhkjhkjhk","kol":7.00,"cena":7.00,"vkupnot":47.00},{"smetki":null,"trId":5,"skID":4,"Artikal":"lkjlkjlk","kol":8.00,"cena":8.00,"vkupnot":64.00},{"smetki":null,"trId":6,"skID":5,"Artikal":"gdfg","kol":5.00,"cena":5.00,"vkupnot":25.00},{"smetki":null,"trId":7,"skID":6,"Artikal":"gdfg","kol":5.00,"cena":5.00,"vkupnot":25.00},{"smetki":null,"trId":8,"skID":7,"Artikal":"gagaggag","kol":5.00,"cena":55.00,"vkupnot":275.00},{"smetki":null,"trId":9,"skID":7,"Artikal":"ggg","kol":4.00,"cena":65.00,"vkupnot":260.00}]
You can add the values from response itself without reading from DOM.
Try this
$(document).ready(function() {
//Call EmpDetails jsonResult Method
$.getJSON("/smetkis/getTrosokList",
function(json) {
var tr;
var sum = 0; //initialising sum
for (var i = 0; i < json.length; i++) {
if (json[i].skID == '#Html.DisplayFor(model => model.smID)') {
tr = $('<tr />');
tr.append("<td >" + json[i].Artikal + "</td>");
tr.append("<td>" + json[i].kol + "</td>");
tr.append("<td>" + json[i].cena + "</td>");
tr.append($('<td class="vkupno1">' + json[i].vkupnot + '</td>'));
$('table').append(tr);
sum += parseFloat(json[i].vkupnot); //adding directly from the response
}
}
$('#result').html((sum).toFixed(2).replace(/(\d)(?=(\d{6})+(?!\d))/g, "$1.") + " €");
});
});
And you need to wait for the response before reading the dynamically created DOM elements.

Javascript - cannot read property 'x' of undefined - json

I'm building a table using information from a json object gained from a url and while the table will build and populate a 'cannot read property 'x' of undefined' type error will occur.
The code for getting the json and building the table is:
$.getJSON(url,function(data) {
for (var i = 0; i < 100 || i < data.length; i++) {
tr.append("<td">"+ data[i].Forename + " " + data[i].Surname + "</td>");
tr.append("<td>" + data[i].Workphone + "</td>");
tr.append("<td>" + data[i].id + "</td>");
tr.append("<td>" + data[i].Department + "</td>");
tr.append("<td">" + data[i].Office + "</td>");
tr.append("<td">" + data[i].Floor + "</td>");
tr.append("<td">" + data[i].Room + "</td>");
$('#body').append(tr);
}
}
With a basic example of the json being:
[{
"Forename": "fname",
"Surname": "sname",
"Id": "id",
"Workphone": "phone",
"Department": "department",
"Office": "office",
"Floor": "floor",
"Room": "room"
},
{
"Forename": "fname",
"Surname": "sname",
"Id": "id",
"Workphone": "phone",
"Department": "department",
"Office": "office",
"Floor": "",
"Room": ""
}]
The error is thrown on the first tr.append at data[i].Forename but will occur at the next data[i].property if Forename is removed.
Any help would be appreciated. Thanks.
First of JSON is case sensitive so calling 'id' instead of 'Id' is not going to work.
Secondly you open quotes where not quotes should be. Around the <td>'s.
Third: Where does the variable tr come from? is it defined above this code, otherwise
you should define it somewhere before using it.
Fourth: Do you want to append to the tr to the <body> tag or an element with 'id' #body. You are doing the latter!
Edit: Added the || && suggestion of musefan.
This should work (untested):
$.getJSON(url, function(data) {
for (var i = 0; i < 100 && i < data.length; i++) {
tr.append("<td>" + data[i].Forename + " " + data[i].Surname + "</td>");
tr.append("<td>" + data[i].Workphone + "</td>");
tr.append("<td>" + data[i].Id + "</td>");
tr.append("<td>" + data[i].Department + "</td>");
tr.append("<td>" + data[i].Office + "</td>");
tr.append("<td>" + data[i].Floor + "</td>");
tr.append("<td>" + data[i].Room + "</td>");
$("#body").append(tr);
}
}
Try this one:
for (var i = 0; i < 100 || i < data.length; i++) {
tr.append("<td>"+ data[i].Forename + " " + data[i].Surname + "</td>");
tr.append("<td>" + data[i].Workphone + "</td>");
tr.append("<td>" + data[i].id + "</td>");
tr.append("<td>" + data[i].Department + "</td>");
tr.append("<td">" + data[i].Office + "</td>");
tr.append("<td">" + data[i].Floor + "</td>");
tr.append("<td">" + data[i].Room + "</td>");
$('#body').append(tr);
}`

Ordering JSON data in a table

I am creating a "leaderboard" page as an external component to a Facebook game.
Basically the app is passing me data through a given JSON response file ('score.json' which contains data objects with three keys: Name, Team, Score), and I am parsing this into an HTML table using the code below:
$(document).ready(function(){
$.getJSON("score.json",
function (data) {
var tr;
for (var i = 0; i < data.length; i++) {
tr = $('<tr/>');
tr.append("<td>" + data[i].User_Name + "</td>");
tr.append("<td>" + data[i].score + "</td>");
tr.append("<td>" + data[i].team + "</td>");
$('table').append(tr);
}
});
});
What I need to do:
Display these table rows in descending order based on the "score" value.
Add a "rank" column with a dynamically generated number inserted with each row
I am just a beginner with JavaScript so any help would be much appreciated.
EDIT: Solved. Final code below:
$(document).ready(function(){
$.getJSON("score.json",
function (data) {
var tr;
data.sort(function(a,b) { return parseFloat(b.score) - parseFloat(a.score) } );
var rank = 1;
for (var i = 0; i < data.length; i++) {
tr = $('<tr/>');
tr.append("<td>" + rank + "</td>");
tr.append("<td>" + data[i].User_Name + "</td>");
tr.append("<td>" + data[i].score + "</td>");
tr.append("<td>" + data[i].team + "</td>");
$('table').append(tr);
rank = rank +1;
}
});
});
you can use this to sort your array :
json.sort(function(a,b) { return parseFloat(b.score) - parseFloat(a.score) } );
Here is the jsFiddle.

Table generated in by Javascript not displaying

This table is not displaying in my html file: can anyone see an obvious mistake? I've been staring at it for hours!
<div id="data_list">
<script type="text/javascript">
document.write("<table border='1' rules='rows' cellspacing='0'>")
document.write("<tr>");
document.write("<th>Date</th><th>Amount</th><th>First Name</th>");
document.write("<th>Last Name</th><th>Address</th>");
document.write("</tr>");
for (i=0;i<=amount.length;i++){
if (i%2=0){
document.write(<tr>);
}else{
document.write("<tr class='yellowrow'>");
}
document.write("<td>" + date[i] + "</td class='amt'>" + amount[i]+ "</td>");
document.write("<td>" +firstName[i] + "</td><td>" + lastName[i] + "</td>");
document.write("<td>" + street[i] + "<br />" + city[i] + ", " +state[i]+ "" + zip[i] + "</td>");
document.write("</tr>");
}
document.write("</table>");
</script>
Here:
if (i%2=0){
document.write(<tr>);
}else{
document.write("<tr class='yellowrow'>");
}
should be
if (i%2==0){
document.write('<tr>');
}else{
document.write("<tr class='yellowrow'>");
}
i%2=0 should be i%2==0
Also, <tr> should be a string '<tr>'

Categories