javascript loop array and object data in one table - javascript

I have array and object data i want to call those together.
var data = [
{"number": "PA1234","name": "John"},
{"number": "JM344","name": "jessi"},
{"number": "ML567","name": "Monty"}
];
var costing= {
"cost": 10,
"cost": 20,
"cost": 30,
};
Display Format in table
<pre>
<table>
<tr>
<td>number</td>
<td>name</td>
<td>cost</td>
</tr>
</table>
<pre>
I have done so far but don't know how to called the object costing
var records=$("<table/>").attr("id","tabs");
$("#table").append(records);
for(var j=0;j<data .length;j++)
{
var tr="<tr>";
var td1="<td>"+data [j]["number"]+"</td>";
var td2="<td>"+data [j]["name"]+"</td>";
$("#tabs").append(tr+td1+td2+td3);
}

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<title>
</title>
<style>
#t, tr, th, td{
border: 1px solid black;
}
</style>
</head>
<body>
<table id="t" cellpadding="10">
<tr>
<th>
Number
</th>
<th>
Name
</th>
<th>
Cost
</th>
</tr>
</table>
</body>
<script>
var number = ['PA1234', 'JM344', 'ML567'], name = ['John', 'Jessi', 'Monty'], costing = [30, 30, 30];
for(var i=0;i<3;i++) {
$("#t").append('<tr><td>' + number[i] + '</td><td>' + name[i] + '</td><td>' + costing[i] + '</td></tr>');
}
</script>
</html>
This is what you want

Had to change some things with your second object, costing. I don't think you can have the same key names on different values, you wouldn't be able to iterate over them. Now you can do two approaches:
var data = [
{"number": "PA1234","name": "John"},
{"number": "JM344","name": "jessi"},
{"number": "ML567","name": "Monty"}
];
var costing = {
"cost0": 10,
"cost1": 20,
"cost2": 30,
};
document.addEventListener("DOMContentLoaded", () => {
const place = document.getElementById("place").firstElementChild
const table = document.createElement("table")
for(let i = 0; i < data.length; i++){
let tr = document.createElement("tr")
let tdNumber = document.createElement("td")
let tdName = document.createElement("td")
let tdCost = document.createElement("td")
tdNumber.innerText = data[i].number
tdName.innerText = data[i].name
tdCost.innerText = costing["cost"+i]
tr.appendChild(tdNumber)
tr.appendChild(tdName)
tr.appendChild(tdCost)
table.appendChild(tr)
}
place.appendChild(table)
})
However personally i would change your costing object to this:
var costing2 = [
10,20,30
]
And change the for loop to this:
for(let i = 0; i < data.length; i++){
let tr = document.createElement("tr")
let tdNumber = document.createElement("td")
let tdName = document.createElement("td")
let tdCost = document.createElement("td")
tdNumber.innerText = data[i].number
tdName.innerText = data[i].name
tdCost.innerText = costing2[i]
tr.appendChild(tdNumber)
tr.appendChild(tdName)
tr.appendChild(tdCost)
table.appendChild(tr)
}
Where place is the spot of the div tag in the html. Not the best solution but it works, putting down the html code aswell if you want that:
<html>
<head>
<script src="./file.js"></script>
</head>
<body>
<div id="place">
<pre>
</pre>
</div>
</body>
</html>

Related

How to create an HTML table from an array of objects?

I need to generate a table from an array of objects.
For example, the array is:
let arr = [{name: 'Player1',score:10},
{name: 'Player2',score: 7},
{name: 'Player3',score:3}]
And the HTML output should be:
Name
Score
Player1
10
PLayer2
7
Player3
3
I could not think of a way to achieve this through vanilla JS.
Also, after the table is created, how will I apply CSS to it?
Any help would be appreciated.
You can loop through the array and for each element add a row to a newly forged table that will be added to the document at the end.
This is a demo:
let players = [
{name: 'Player1',score:10},
{name: 'Player2',score: 7},
{name: 'Player3',score:3}
];
const newTable = document.createElement("table");
newTable.innerHTML = "<thead><th>Player</th><th>Score</th></thead>";
for(player of players){
const newRow = document.createElement("tr");
const tdPlayer = document.createElement("td");
const tdScore = document.createElement("td");
tdPlayer.textContent = player.name;
tdScore.textContent = player.score;
newRow.appendChild(tdPlayer);
newRow.appendChild(tdScore);
newTable.appendChild(newRow);
}
const target = document.getElementById('target');
target.appendChild(newTable);
table{
border: solid 1px black;
}
table td{
border: solid 1px black;
}
<div id="target">
</div>
You can use something like
<body>
<div class="main-container">
<table>
<thead>
<tr>
<th>player</th>
<th>score</th>
</tr>
</thead>
<tbody></tbody>
</table>
</div>
<script>
const data = [{ name: 'Player 1', score: 10 },
{ name: 'Player 2', score: 7 },
{ name: 'Player 3', score: 3 }]
const table = document.querySelector('tbody')
data.forEach((item) => {
table.innerHTML = table.innerHTML + `<tr>
<td>${item.name}</td>
<td>${item.score}</td>
</tr>`
})
</script>

Html table add column with javascript

I am obviously very new to JS. I need to solve a problem where i can't change the HTML and CSS-file. From the HTML-file I am supposed to:
add a column with the header "Sum". (Already did that)
add a row att the bottom with the div id "sumrow". (Did that as well)
add a button at the end. (Did that)
add the total from columns "Price and Amount" into column "Sum" when button is clicked
(This where I am lost)
And like I said I can't change anything in HTML and CSS-files.
// Create a newelement and store it in a variable
var newEl = document.createElement('th');
//Create a text node and store it in a variable
var newText = document.createTextNode('Summa');
//Attach the newtext node to the newelement
newEl.appendChild(newText);
//Find the position where the new element should be added
var position = document.getElementsByTagName('tr')[0];
//Insert the newelement into its position
position.appendChild(newEl);
// Find a <table> element with id="myTable":
var table = document.getElementById("pricetable");
// Create an empty <tr> element and add it to the 1st position of the table:
var row = table.insertRow(-1);
// Insert new cells (<td> elements) at the 1st and 2nd position of the "new" <tr> element:
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
var cell3 = row.insertCell(2);
var cell4 = row.insertCell(3);
var cell5 = row.insertCell(4);
var cell6 = row.insertCell(5);
// Add some text to the new cells:
cell1.innerHTML = "";
cell2.innerHTML = "";
cell3.innerHTML = "";
cell4.innerHTML = sumVal;
cell5.innerHTML = "";
cell6.innerHTML = "";
//Puts divid sumrow
row.setAttribute("id", "sumrow");
var table = document.getElementById("pricetable"), sumVal = 0;
for(var i = 1; i < table.rows.length; i++)
{
sumVal = sumVal + parseInt(table.rows[i].cells[3].innerHTML);
}
//Creates button
var button = document.createElement("button");
button.innerHTML = "Beräkna pris";
// 2. Append somewhere
var body = document.getElementsByTagName("tbody")[0];
body.appendChild(button);
button.addEventListener("click", medelVarde, true);
button.addEventListener("click", raknaUtMedelvarde, true);
button.setAttribute("class", "btn-primary");
function medelVarde(celler){
var summa = 0;
for(var i = 3; i < celler.length -1; i++){ //Räknar igenom från cell nr 4
var nuvarandeVarde = celler[i].firstChild.nodeValue;
summa = summa + parseInt(nuvarandeVarde);
}
var medel = summa / 1;
return medel;
}
function raknaUtMedelvarde(){
var tabell = document.getElementById("pricetable");
var rader = tabell.getElementsByTagName("tr");
for(var i = 1; i < rader.length; i++){
var tabellceller = rader[i].getElementsByTagName("td"); //Pekar på de td-element som vi har hämtat
var medel = medelVarde(tabellceller);
var medeltext = document.createTextNode(medel);
var medelelement = tabellceller[tabellceller.length - 1];
var row2 = table.insertRow(-1);
medelelement.appendChild(medeltext.cloneNode(true));
.table {
background: white;
}
tr#sumrow {
background-color: #cce4ff;
}
tr#sumrow td:first-child::after{
content: "\a0";
}
<!DOCTYPE html>
<html lang="sv">
<head>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
<title>Handling calculations and tables</title>
<link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css" />
<link rel="stylesheet" type="text/css" href="style/style.css" />
</head>
<body>
<div class="container">
<div id="header" class="text-center px-3 py-3 pt-md-5 pb-md-4 mx-auto">
<h1 class="display-4">Home Electronics</h1>
<p class="lead">Excellent prices on our hone electronics</p>
</div>
<div id="content">
<table id="pricetable" class="table table-hover">
<thead class="thead-dark">
<tr>
<th>Articlenr</th>
<th>Producttype</th>
<th>Brand</th>
<th>Price</th>
<th>Amount</th>
</tr>
</thead>
<tbody>
<tr>
<td>23456789</td>
<td>Telephone</td>
<td>Apple</td>
<td>6500</td>
<td>
<input type="text" size="3" value="1" />
</td>
</tr>
<tr>
<td>22256289</td>
<td>Telephone</td>
<td>Samsung</td>
<td>6200</td>
<td>
<input type="text" size="3" value="1" />
</td>
</tr>
<tr>
<td>24444343</td>
<td>Telephone</td>
<td>Huawei</td>
<td>4200</td>
<td>
<input type="text" size="3" value="1" />
</td>
</tr>
<tr>
<td>19856639</td>
<td>Tablet</td>
<td>Apple</td>
<td>4000</td>
<td>
<input type="text" size="3" value="1" />
</td>
</tr>
<tr>
<td>39856639</td>
<td>Tablet</td>
<td>Samsung</td>
<td>2800</td>
<td>
<input type="text" size="3" value="1" />
</td>
</tr>
<tr>
<td>12349862</td>
<td>Tablet</td>
<td>Huawei</td>
<td>3500</td>
<td>
<input type="text" size="3" value="1" />
</td>
</tr>
</tbody>
</table>
</div>
</div>
<!-- add this script as snippet in this question -->
<!-- <script src="scripts/calculate.js"></script> -->
</body>
</html>
Or code is available on https://jsfiddle.net/cmyr2fp6/
button.addEventListener("click", medelVarde, true);
button.addEventListener("click", raknaUtMedelvarde, true);
For the button click event listener, you don't have to add the medelVarde function.
Also, speaking of that function, I'm not really sure what's happening there. Are you trying to multiply the price and the amount? If so, you can just get the price cell's text and multiply it by the amount input's value (converting to Number the values before multiplying).
const [,,, priceCell, amountCell, sumCell] = row.querySelectorAll('td');
const price = Number(priceCell.innerText);
const amount = Number(amountCell.querySelector('input').value);
const sum = price * amount;
The [,,, priceCell, amountCell, sumCell] is just a short-hand for getting the cells you want from the row (destructuring assignment. querySelectorAll returns a NodeList wherein you can get the element by index.
function setUp() {
// Set up table.
const table = document.getElementById('pricetable');
const headerRow = table.querySelector('thead tr');
const sumHeader = headerRow.insertCell();
const tbody = table.querySelector('tbody');
const sumTotalRow = tbody.insertRow();
const sumTotalCell = sumTotalRow.insertCell();
sumHeader.innerText = 'Summa';
sumTotalCell.colSpan = '5';
sumTotalCell.innerText = 'Total';
tbody.querySelectorAll('tr').forEach(row => row.insertCell());
// Set up button.
const btn = document.createElement('button');
btn.innerText = 'Beräkna pris';
btn.addEventListener('click', () => {
let total = 0;
tbody.querySelectorAll('tr').forEach((row, i, arr) => {
if (i < arr.length - 1) {
const [,,, priceCell, amountCell, sumCell] = row.querySelectorAll('td');
const price = Number(priceCell.innerText);
const amount = Number(amountCell.querySelector('input').value);
const sum = price * amount;
sumCell.innerText = sum;
total += sum;
} else {
const totalCell = row.querySelector('td:last-child');
totalCell.innerText = total;
}
});
});
document.body.appendChild(btn);
}
setUp();
Hey ZioPaperone welcome to the JS World :-)
First of all I would recommend to wrap you logic into functions, eg
appendRow() {
//put append row logic here
}
Now let's move on to your question, appending a column is a bit more of a trick then appending a row. You might noticed already that the DOM-Structure is a bit more complex. So for a row you could you correctly has added a node to your tbody.
For a column we need to learn how to create a cell and how we add an entry to the thead. We will use the insertCell() method to insert cells, for thead cells that won't work, so we need to add the th with createElement() and append it with appendChild()
function appendColumn() {
// insertCell doesn't work for <th>-Nodes :-(
var tableHeadRef = document.getElementById('pricetable').tHead; // table reference
var newTh = document.createElement('th');
tableHeadRef.rows[0].appendChild(newTh); // inser new th in node in the first row of thead
newTh.innerHTML = 'thead title';
// open loop for each row in tbody and append cell at the end
var tableBodyRef = document.getElementById('pricetable').tBodies[0];
for (var i = 0; i < tableBodyRef.rows.length; i++) {
var newCell = tableBodyRef.rows[i].insertCell(-1);
newCell.innerHTML = 'cell text'
}
}
EDIT:
To sum up values in col u can use the same approach. I broke down the nodes for better understanding. You also might want to add a check if your table data contains a number with isNaN().
function sumColumn(tableId, columnIndex) {
var tableBodyRef = document.getElementById(tableId).tBodies[0];
var sum = 0; // Initialize sum counter with 0
for (var i = 0; i < tableBodyRef.rows.length; i++) {
var currentRow = tableBodyRef.rows[i]; //access current row
var currentCell = currentRow.cells[columnIndex]; // look for the right column
var currentData = currentCell.innerHTML; // grab cells content
var sum += parseFloat(currentData); // parse content and add to sum
}
return sum;
}

replace the table data with the selected data(javascript)

javascript beginner here, trying to code and learn.
I have a table filled with data (fetch from url) and that data is
{
"france": "paris",
"finland": "helsinki",
"sweden": "stockholm",
"tajikistan": "dushanbe",
"uzbekistan ": "toshkent",
"china": "peking",
"dole": {
"Key": "fhd699f"
}
}
and under the table I have a select box (the data of it also fetched from url) its data is this
[
{"nimi": "tili","id": "48385","somewhere": "nassau","somewhere2": "bamako","somewhere3": "rabat","somewhere4": "baku"},
{"nimi": "tili","id": "789642","somewhere": "windhoek","somewhere2": "podgorica","somewhere3": "niamey","somewhere4": "islamabad"}
]
i want to replace the table data with the selected data ( i mean everything) even table's <th> also, for example table's <th> is 'france' and value is 'paris' but after replace table's <th> should be 'nimi' and value 'tili' according to select box data.
here is my code (as you can see 'tajikistan','uzbekistan','china' for some reason not going to their places in table):
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css">
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.6.3/css/all.css" integrity="sha384-UHRtZLI+pbxtHCWp1t77Bi1L4ZtiqrqD80Kn4Z8NTSRyMA2Fd33n5dQ8lWUE00s/" crossorigin="anonymous">
<style>
</style>
</head>
<body>
<div class="container">
<table class="table ">
<thead>
<tr>
<th class="table-success">france</th>
<th class="table-success">finland</th>
<th class="table-success">sweden</th>
</tr>
</thead>
<tbody id="tiedot">
</tbody>
<thead>
<tr>
<th class="table-success">tajikistan</th>
<th class="table-success">uzbekistan</th>
<th class="table-success">china</th>
</tr>
</thead>
<tbody id="tiedot2">
</tbody>
</table>
<select id="valittu" name="name"></select>
</div>
<script>
fetch(
"https://tdejdjd***",
{
method: "GET",
headers: {
"x-api-key": "i****y"
}
}
)
.then((res) => {
res
.json()
.then((data) => {
tableupdating(data, ['france','finland','sweden','tajikistan','uzbekistan','china']);
})
.catch((err) => {
console.log("ERROR: " + err);
});
});
function tableupdating(data, values) {
const totable = document.getElementById("tiedot");
const totable2 = document.getElementById("tiedot2");
totable.innerHTML = "";
totable2.innerHTML = "";
var komb = "";
var komb2 = "";
komb += "<tr>";
komb2 += "<tr>";
values.forEach(value => {
komb += "<td>" + data[value] + "</td>";
})
values.forEach(value => {
komb2 += "<td>" + data[value] + "</td>";
})
totable.insertAdjacentHTML("beforeend", komb);
totable2.insertAdjacentHTML("beforeend", komb2);
}
let dataArray;
fetch(
"https://tdejdjd***",
{
method: "GET",
headers: {
"x-api-key": "i****y"
}
}
)
.then((res) => {
res.json().then((data) => {
dataArray = data;
updateSelect(data, ['nimi','id']);
});
});
function updateSelect(data, values) {
for (var i = 0; i < data.length; i++) {
var Valittu = document.getElementById("valittu");
var option = document.createElement("option");
values.forEach(value => {
option.textContent += data[i][value] + ' '
})
Valittu.appendChild(option);
}
}
document.getElementById("valittu").addEventListener("change", function (event) {
const chosenID = event.target.value.split(" ")[1];
const chosenData = dataArray.filter((data) => data.id === chosenID)[0];
tableupdating(chosenData, ['nimi', 'id', 'somewhere','somewhere2','somewhere3','somewhere4']);
});
</script>
</body>
</html>
as spoken in chat, here is new code, it is working but for some reason these three are in same line and not on their places : komb += "<td>"+tiedot.tajikistan+"</td>";
komb += "<td>"+tiedot.uzbekistan+"</td>";
komb += "<td>"+tiedot.china+"</td></tr>";
code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css">
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.6.3/css/all.css" integrity="sha384-UHRtZLI+pbxtHCWp1t77Bi1L4ZtiqrqD80Kn4Z8NTSRyMA2Fd33n5dQ8lWUE00s/" crossorigin="anonymous">
<style>
</style>
</head>
<body onload="fillTheBox();">
<div class="container">
<table class="table" id="myTable">
<thead>
<tr>
<th class="table-success">france</th>
<th class="table-success">finland</th>
<th class="table-success">sweden</th>
</tr>
</thead>
<tbody id="tiedot">
</tbody>
<thead>
<tr>
<th class="table-success">tajikistan</th>
<th class="table-success">uzbekistan</th>
<th class="table-success">china</th>
</tr>
</thead>
</table>
<select id="valittu" name="name" onchange="changed()"></select>
</div>
<script>
fetch("https://qj",
{
method: "GET",
headers: {
"x-api-key": ""
}
}
).then(res =>{
res.json().then(tiedot => {
console.log(tiedot);
var komb ="";
komb +="<tr>";
komb += "<td>"+tiedot.france+"</td>";
komb += "<td>"+tiedot.finland+"</td>";
komb += "<td>"+tiedot.sweden+"</td>";
komb += "<td>"+tiedot.tajikistan+"</td>";
komb += "<td>"+tiedot.uzbekistan+"</td>";
komb += "<td>"+tiedot.china+"</td></tr>";
document.getElementById("tiedot").insertAdjacentHTML("beforeend", komb );
}
)
})
var dataArray = [
{ "nimi": "tili", "id": "48385", "somewhere": "nassau", "somewhere2": "bamako", "somewhere3": "rabat", "somewhere4": "baku" },
{ "nimi": "tili", "id": "789642", "somewhere": "windhoek", "somewhere2": "podgorica", "somewhere3": "niamey", "somewhere4": "islamabad" }
]
function fillTheBox() {
var selectBox = document.getElementById("valittu");
var option = document.createElement("option");
option.value = dataArray[0];
option.text = dataArray[0].nimi+' '+dataArray[0].id;
selectBox.add(option);
var option1 = document.createElement("option");
option1.value = dataArray[1];
option1.text = dataArray[1].id;
selectBox.add(option1);
}
function changed() {
var e = document.getElementById("valittu");
var selectedObjectID = e.options[e.selectedIndex].text;
chosenData = dataArray.filter((data) => data.id === selectedObjectID)[0];
var myTable = document.getElementById("myTable");
myTable.innerHTML = "";
generateTable(myTable, chosenData);
}
function generateTable(table, data) {
let row1 = table.insertRow();
row1.className = "table-success";
let row2 = table.insertRow();
let row3 = table.insertRow();
row3.className = "table-success";
let row4 = table.insertRow();
var counter = 1;
for (key in data) {
if (counter<=3) {
let cell = row1.insertCell();
let text = document.createTextNode(key);
cell.appendChild(text);
let cell2 = row2.insertCell();
let text2 = document.createTextNode(data[key]);
cell2.appendChild(text2);
} else {
let cell = row3.insertCell();
let text = document.createTextNode(key);
cell.appendChild(text);
let cell2 = row4.insertCell();
let text2 = document.createTextNode(data[key]);
cell2.appendChild(text2);
}
counter++;
}
}
</script>
</body>
</html>
I created a basic demo to show the logic. Firs of all give an id to your table. And create a onChange event for your select box. In your event function edit your table content with innerHTML property. Just focus on change() and generateTable() functions in my code
<body onload="fillTheBox();">
<div class="container">
<table class="table" id="myTable">
<thead>
<tr>
<th class="table-success">france</th>
<th class="table-success">finland</th>
<th class="table-success">sweden</th>
</tr>
</thead>
<tbody id="tiedot">
</tbody>
<thead>
<tr>
<th class="table-success">tajikistan</th>
<th class="table-success">uzbekistan</th>
<th class="table-success">china</th>
</tr>
</thead>
</table>
<select id="valittu" name="name" onchange="changed()"></select>
</div>
<script>
var dataArray = [
{ "nimi": "tili", "id": "48385", "somewhere": "nassau", "somewhere2": "bamako", "somewhere3": "rabat", "somewhere4": "baku" },
{ "nimi": "tili", "id": "789642", "somewhere": "windhoek", "somewhere2": "podgorica", "somewhere3": "niamey", "somewhere4": "islamabad" }
]
function fillTheBox() {
var selectBox = document.getElementById("valittu");
var option = document.createElement("option");
option.value = dataArray[0];
option.text = dataArray[0].id;
selectBox.add(option);
var option1 = document.createElement("option");
option1.value = dataArray[1];
option1.text = dataArray[1].id;
selectBox.add(option1);
}
function changed() {
var e = document.getElementById("valittu");
var selectedObjectID = e.options[e.selectedIndex].text;
chosenData = dataArray.filter((data) => data.id === selectedObjectID)[0];
var myTable = document.getElementById("myTable");
myTable.innerHTML = "";
generateTable(myTable, chosenData);
}
function generateTable(table, data) {
let row1 = table.insertRow();
row1.className = "table-success";
let row2 = table.insertRow();
row2.className = "table-success";
let row3 = table.insertRow();
row3.className = "table-success";
let row4 = table.insertRow();
row4.className = "table-success";
var counter = 1;
for (key in data) {
if (counter<=3) {
let cell = row1.insertCell();
let text = document.createTextNode(key);
cell.appendChild(text);
let cell2 = row2.insertCell();
let text2 = document.createTextNode(data[key]);
cell2.appendChild(text2);
} else {
let cell = row3.insertCell();
let text = document.createTextNode(key);
cell.appendChild(text);
let cell2 = row4.insertCell();
let text2 = document.createTextNode(data[key]);
cell2.appendChild(text2);
}
counter++;
}
}
</script>
</body>
</html>
UPDATE:
To separate the fields mentioned in question add a <tr> element between them.
komb +="<tr>";
komb += "<td>"+tiedot.france+"</td>";
komb += "<td>"+tiedot.finland+"</td>";
komb += "<td>"+tiedot.sweden+"</td>";
komb +="</tr><tr>";
komb += "<td>"+tiedot.tajikistan+"</td>";
komb += "<td>"+tiedot.uzbekistan+"</td>";
komb += "<td>"+tiedot.china+"</td></tr>";

Javascript / Jquery Help - Calling functions from select menu

I Need some help with adding interactivity to this page.
I'm new to jQuery and this stuff is probably simple but its been driving me nuts!
Its just a footy team with different players details stored in objects in an array called Squad_list
Squad_List.js
var squad = [
{
number: 1,
pic: 'img/HIBBERD_M_t.png',
name: 'Michael',
surname: 'Hibberd',
height: '186 cm',
weight: '86 kg',
debut: 2011,
position: ['defender'],
games: 85,
goals: 11
},
{
number: 2,
pic: 'img/BELLCHAMBERS_T_t.png',
name: 'Tom',
surname: 'Bellchambers',
height: '202 cm',
weight: '106 kg',
debut: 2008,
position: ['ruck'],
games: 79,
goals: 53
},
{
number: 3,
pic: 'img/CHAPMAN_P_t.png',
name: 'Paul',
surname: 'Chapman',
height: '179 cm',
weight: '87 kg',
debut: 2000,
position: ['foward'],
games: 280,
goals: 366,
goals15: 8
},
];
etc etc
I have different functions to create a listQuery from the Squad_List based on different positions, games played etc ie addListDefender creates a list of players whose position = defender
I have a drawtable function to write the info to the page
I've got a select menu to pick the different listQuery options the values named after the relevant listQuery function it should call
App.js
var listQuery = [];
// Draw table from 'listQuery' array of objects
function drawTable(tbody) {
var tr, td;
tbody = document.getElementById(tbody);
// loop through data source
// document.write(tbody);
for (var i = 0; i < listQuery.length; i++) {
tr = tbody.insertRow(tbody.rows.length);
td = tr.insertCell(tr.cells.length);
td.setAttribute("align", "center");
td.innerHTML = "<p>" + listQuery[i].number + "</p>";
td = tr.insertCell(tr.cells.length);
td.innerHTML = '<img src="' + listQuery[i].pic + '">';
td = tr.insertCell(tr.cells.length);
td.innerHTML = listQuery[i].name + " " + listQuery[i].surname;
td = tr.insertCell(tr.cells.length);
td.innerHTML = listQuery[i].height;
td = tr.insertCell(tr.cells.length);
td.innerHTML = listQuery[i].weight;
td = tr.insertCell(tr.cells.length);
td.innerHTML = listQuery[i].debut;
td = tr.insertCell(tr.cells.length);
if (listQuery[i].position.length > 1) {
td.innerHTML += listQuery[i].position[0] + " / " + listQuery[i].position[1];
} else {
td.innerHTML += listQuery[i].position;
}
td = tr.insertCell(tr.cells.length);
td.innerHTML = listQuery[i].games;
td = tr.insertCell(tr.cells.length);
td.innerHTML = listQuery[i].goals;
td = tr.insertCell(tr.cells.length);
}
}
//Display entire list
var displayList = function() {
listQuery = squad;
};
//Take players from list that position = foward
var addListFoward = function() {
for (i = 0; i < squad.length; i++) {
if (squad[i].position.indexOf("foward") >= 0) {
listQuery.push(squad[i]);
console.log(squad[i]);
}
}
}
//Take players from list whose position = defender
var addListDefender = function() {
for (i = 0; i < squad.length; i++) {
if (squad[i].position === "defender") {
listQuery.push(squad[i]);
console.log(squad[i]);
}
}
}
//Take 10 items from player list in order of most games
var addListGames = function () {
squad.sort(function(a, b){
return b.games-a.games
})
listQuery = squad;
listQuery.length = 10;
}
// Site starts with Display Entire List
displayList();
drawTable("output");
//Generate list query on change select button from select options value
$('#select').change(function() {
});
//display selection from select button onclick go button
$('#go').click(function() {
// alert("go has been click!");
drawTable("output");
});
Basically when the select menu is changed I want to call a function equal to the select value and then redraw the table with the go button.....but the various things I've tried on $('#select') and $('#go') don't work.
Any help much appreciated!!!
<!DOCTYPE html>
<html lang="en">
<head>
<meta cahrset="UTF-8">
<title>Bombers Squad</title>
<link rel="stylesheet" href="css/styles.css">
</head>
<body>
<div class="header">
<div class="main-title">
<h1>Bombers Squad</h1>
</div>
<div class="logo">
<img src="img/logo-2x.png" alt="Bombers logo">
</div>
</div>
<div class="main-field">
<form>
<label for="select">View Bombers Squad:</label>
<select id="select" name="bombers_list">
<option value="displayList">Display Entire List</option>
<option value="addListFoward">Display Fowards</option>
<option value="addListMidfield">Display Midfielders</option>
<option value="addListDefender">Display Defenders</option>
<option value="addListRuck">Display Rucks</option>
<option value="addListGames">Display Most Games</option>
<option value="addGoals2015">2015 Goal kickers</option>
<option value="addBF2015">2015 Best & Fairest Votes</option>
</select>
<button id="go" type="submit">Go</button>
</form>
<table id="players">
<caption>Player Information</caption>
<thead>
<tr>
<th scope="col">Number</th>
<th scope="col">Picture</th>
<th scope="col">Name</th>
<th scope="col">Height</th>
<th scope="col">Weight</th>
<th scope="col">Debut</th>
<th scope="col">Position</th>
<th scope="col">Games</th>
<th scope="col">Goals</th>
</tr>
</thead>
<tbody id="output">
</tbody>
</table>
</div>
<script src="//code.jquery.com/jquery-1.11.3.min.js"></script>
<script src="js/squad_list.js"></script>
<script src="js/app.js"></script>
</body>
</html>
JsFidder
Seems you just forget to include jquery or not referenced properly
check the below Answer & working demo
or simply add
$(function(){
$('#select').change(function () {
});
//display selection from select button onclick go button
$('#go').click(function () {
alert("go has been click!");
drawTable("output");
});
})

Iterating through different text box in java script and assigning values

I was trying to iterate in loop through text boxes and assign values to it. I have created three array list ids[],id1s[],id2s[].
values in ids[] have to be populated in the first column and its coming fine. but values in id1s[] and id2[] need to be populated in the 2nd and 3rd column. loop run 5 times. first times it populating in the first row, but from next time onward its overriding the first row.. and not coming to second row
Below is my code :--
<!DOCTYPE html>
<html>
<head>
<script>
function start()
{
var ids = ["A", "B", "C", "D", "E"];
var id1s = [1,2,3,4,5];
var id2s = [6,7,8,9,10];
for (var i = 0; i < ids.length; i++){
var value=ids[i];
addrow(value);
addData(id1s[i], id2s[i]);
}
}
function addrow(value)
{
var test1 = value+'1';
var test2 = value+'2';
var TABLE = document.getElementById('tableId');
var BODY = TABLE.getElementsByTagName('tbody')[0];
var TR = document.createElement('tr');
var TD1 = document.createElement('td');
var TD2 = document.createElement('td');
var TD3 = document.createElement('td');
TD1.innerHTML = value;
TD2.innerHTML = "<input type='text' id='test1' value=''>";
TD3.innerHTML = "<input type='text' id='test2' value=''>";
TR.appendChild (TD1);
TR.appendChild (TD2);
TR.appendChild (TD3);
BODY.appendChild(TR);
}
function addData(num,num1)
{
alert("Showing assignment of values");
document.getElementById("test1").value=num;
document.getElementById("test2").value=num1;
}
</script>
</head>
<body>
<table id="tableId" border='1' cellspacing='0' cellpadding='0'>
<tr>
<td>Variable</td>
<td>Value1</td>
<td>Value2</td>
</tr>
<button type="button" onclick="start()">Display</button>
</table>
</body>
please suggest how to iterate through the text boxes created in 2nd and 3rd column
I modified your addrow and addData functions
For addrow function
You have to use the value inside test1 and test2 to form the input ids
like this
TD2.innerHTML ="<input type='text' id='"+ test1 + "' value=''>";
TD3.innerHTML ="<input type='text' id='"+ test2 + "' value=''>";
for addData function bring in the 'value' variable as a parameter
and change the document.getElementById statements as
document.getElementById(value + "1").value=num;
document.getElementById(value + "2").value=num1;
Please check jsFiddle http://jsfiddle.net/TbGcD/1/
In my experience, something like this should provide decent performance
<!DOCTYPE html>
<html>
<head>
<script>
function start()
{
var ids = ["A", "B", "C", "D", "E"];
var id1s = [1,2,3,4,5];
var id2s = [6,7,8,9,10];
var table= document.getElementById('tableId').getElementsByTagName('tbody')[0];
for (var i = 0; i < ids.length; i++){
alert("Showing assignment of values");
table.innerHTML+= '<tr><td>'+ids[i]+'</td><td>'+id1s[i]+'</td><td>'+id2s[i]+'</td></tr>';
}
}
</script>
</head>
<body>
<button type="button" onclick="start()">Display</button>
<table id="tableId" border='1' cellspacing='0' cellpadding='0'>
<tr>
<td>Variable</td>
<td>Value1</td>
<td>Value2</td>
</tr>
</table>
</body>
If you don't need to see each row assigned separately, I suggest doing something like this
<!DOCTYPE html>
<html>
<head>
<script>
function start()
{
var ids = ["A", "B", "C", "D", "E"];
var id1s = [1,2,3,4,5];
var id2s = [6,7,8,9,10];
var table= document.getElementById('tableId').getElementsByTagName('tbody')[0];
var text='';
for (var i = 0; i < ids.length; i++){
text+='<tr><td>'+ids[i]+'</td><td>'+id1s[i]+'</td><td>'+id2s[i]+'</td></tr>';
}
table.innerHTML+= text;
text='';
}
</script>
</head>
<body>
<button type="button" onclick="start()">Display</button>
<table id="tableId" border='1' cellspacing='0' cellpadding='0'>
<tr>
<td>Variable</td>
<td>Value1</td>
<td>Value2</td>
</tr>
</table>
</body>

Categories

Resources