How can I create a multi-option dynamic dropdown in a table? - javascript

I am trying to make a dynamic multi-select option dropdown. The text for the options element in the dropdown are coming from a database that I am fetching. I want each row in the table to have the last column contain this multi-select option dropdown. Right now, the result is it's skipping every row and only on the last row is it displaying all the options multiple times (as amount of times as there are rows). So instead of showing in each row, every row is empty expect the last one and the values are all being showed in the final row. Also, strangely it created empty white space on the right side of the table, like it make new columns. I have attached an image to help visualize this.
How do I display the options properly in each row and how do I make it a multi select dropdown, where if the user clicks one of the options, that option is added to the impact area section.
Thanks.
Image: Image of how it currently looks
Javascript:
//Get Resources and corresponding information and display it in a table
function getResources(){
fetch("______", {
}).then(data => {
var table = document.getElementById("productivity-table");
for(var i=0; i < data.length; i++){
var row = table.insertRow(table.rows.length - 1);
var cell3 = row.insertCell(2);
cell3.classList.add("table-data");
//Cell3 - Create ul and li
var impact_ul = document.createElement("ul");
var impact_li = document.createElement("li");
impact_li.innerHTML = data[i].entity;
impact_li.setAttribute("style", "list-style-type:none");
//Add delete button row
var delete_span = document.createElement("span");
delete_span.className = "delete";
delete_span.innerHTML = "×"
impact_li.appendChild(delete_span);
impact_ul.appendChild(impact_li);
cell3.appendChild(impact_ul);
//Cell5 - Create department dropdown
var dep_dropdown = document.createElement('select');
console.log("dep dropdown", dep_dropdown);
//dep_dropdown.length = 0;
let dep_default = document.createElement('option');
dep_default.text = 'Select Department';
dep_default.disabled = true;
dep_dropdown.add(dep_default);
dep_dropdown.selectedIndex = 0;
fetch("______", {
}).then(data =>{
for(var i=0; i < data.length; i++){
var cell5 = row.insertCell(4);
cell5.classList.add("table-data");
var dep_option = document.createElement('option');
dep_option.text = data[i].dept_name;
dep_option.value = data[i]._id;
dep_dropdown.appendChild(dep_option);
cell5.appendChild(dep_dropdown);
}
}).catch(function(err) {
console.log('Fetch problem: ' + err);
});
}
})
}

here is what you asked for take alook on the snippet
window.onload = function() {
var data = ["option1", "option2", "option3", "option4"];
var table = document.getElementById("productivity-table");
function addslct(dep_dropdown) {
dep_dropdown = document.createElement('select');
dep_dropdown.size = "3";
dep_dropdown.className = "dep_select";
dep_dropdown.id = 'selection';
dep_dropdown.name = 'data options';
dep_dropdown.multiple = "multiple";
dep_dropdown.style.position = "relative";
dep_dropdown.style.width = "100%";
dep_dropdown.style.textAlign = "center";
dep_dropdown.style.color = "darkblue";
return dep_dropdown;
}
function addopts(data) {
var slcts = document.getElementsByClassName('dep_select');
for (var i = 0; i < slcts.length; i++) {
for (var a = 0; a < data.length; a++) {
slcts[i].options.add(optns(data[a], data[a]));
}
}
}
function optns(option, oname) {
var option = document.createElement('option');
option.Value = option;
option.textContent = oname;
return option;
}
table.rows[0].innerHTML += "<th>4</th>";
for (var i = 1; i < table.rows.length; i++) {
var newell = table.rows[i].cells.length;
table.rows[i].insertCell(newell);
table.rows[i].cells[table.rows.length - 1].appendChild(addslct());
}
addopts(data);
document.querySelectorAll('.dep_select').forEach(selectedOptions => {
selectedOptions.addEventListener('click', function() {
var col2 = this.options;
for (var o = 0; o < col2.length; o++) {
var o2 = col2[o];
if (o2.selected == true) {
var rwi = this.parentNode.parentNode.rowIndex;
var cli = this.parentNode.cellIndex;
var cell2 = table.rows[rwi].cells[cli-2];
var slctdopt = o2.value;
if (cell2.innerText.includes(slctdopt) == true) {
var excludez = cell2.innerText.replace("[ "+ slctdopt +" ]", "");
cell2.innerText = excludez + " [ " + slctdopt +" ]";
//cell2.innerText += " [ " + slctdopt +" ]";
} else {
excludez = slctdopt;
cell2.innerText += " [ "+ excludez +" ]";
}
}
}
});
});
}
#productivity-table {
font-family: Arial, Helvetica, sans-serif;
border-collapse: collapse;
width: 100%;
}
#productivity-table td,
#productivity-table th {
border: 1px solid #ddd;
padding: 8px;
}
#productivity-table td {
text-align: center;
color: blue;
margin: auto;
width:20%;
}
#productivity-table tr:nth-child(even) {
background-color: #f2f2f2;
}
#productivity-table tr:hover {
background-color: #ddd;
}
#productivity-table th {
padding-top: 12px;
padding-bottom: 12px;
text-align: center;
background-color: #4CAF50;
color: white;
}
<table class="table1" id="productivity-table">
<tr>
<th>1</th>
<th>2</th>
<th>3</th>
</tr>
<tr>
<td>first</td>
<td></td>
<td>third</td>
</tr>
<tr>
<td>first</td>
<td>[ option2 ]</td>
<td>third</td>
</tr>
<tr>
<td>first</td>
<td>[ option3 ]</td>
<td>third</td>
</tr>
</table>

Related

I am using javascript to convert a large table to a pdf

I wrote this great script to help my team set up the weekly task distribution board, I wrote it using java script, html, and css, they've been doing it for a very long time in pencil on paper. but now i am in the final stage, i would like to convert my table to pdf, and this is where i found it difficult, i did several tests : like convert csv to pdf, it doesn't always give a good table, as it is under html. I would like to add a column at the end of the table for remarks but I think I will try with it later. now i'm just focus on pdf export. to be able to print our table every week and hang it, instead of pencil and a paper.
<table id="timetable">
<body>
<tr>
<td>
<link href="table.css" rel="stylesheet">
<script src="table.js"></script>
</td>
<tr>
<button onclick="exportCSV()">Export CSV</button>
<script src="https://cdnjs.cloudflare.com/ajax/libs/PapaParse/5.1.0/papaparse.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/FileSaver.js/1.3.8/FileSaver.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.5.3/jspdf.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/FileSaver.js/1.3.8/FileSaver.min.js"></script>
<button onclick="exportPDF()">Export PDF</button>
<script src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.1.77/pdfmake.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.1.77/vfs_fonts.js"></script>
</body>
const timetable = document.getElementById("timetable");
const days = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"];
const hours = ["7H", "13H", "20H"];
// Create table headers for days
const daysHeaderRow = document.createElement("tr");
const daysHeaderCell = document.createElement("th");
daysHeaderCell.innerHTML = "Days";
daysHeaderRow.appendChild(daysHeaderCell);
days.forEach(day => {
const dayHeaderCell = document.createElement("th");
dayHeaderCell.innerHTML = day;
dayHeaderCell.colSpan = 3;
daysHeaderRow.appendChild(dayHeaderCell);
});
timetable.appendChild(daysHeaderRow);
// Create table headers for hours
const hoursHeaderRow = document.createElement("tr");
const hoursHeaderCell = document.createElement("th");
hoursHeaderCell.innerHTML = "Hours";
hoursHeaderRow.appendChild(hoursHeaderCell);
for (let i = 0; i < days.length; i++) {
for (let j = 0; j < 3; j++) {
const hourHeaderCell = document.createElement("th");
hourHeaderCell.innerHTML = hours[j];
hoursHeaderRow.appendChild(hourHeaderCell);
}
}
timetable.appendChild(hoursHeaderRow);
// Create row for Mina
const names = ["Khalfi","Redouani", "Daki", "Hamma", "Saadane", "Boughanem", "El Ansari","Badilou","Raoui", "Chouiba", "Dahmane", "Achdad", "Bouryal", "Ettouri", "Saadouni"];
for (let name of names) {
const row = document.createElement("tr");
const nameCell = document.createElement("td");
nameCell.innerHTML = name;
row.appendChild(nameCell);
for (let i = 0; i < days.length; i++) {
for (let j = 0; j < 3; j++) {
const cell = document.createElement("td");
const select = document.createElement("select");
select.classList.add("cell");
const options = [" ", "CP", "ME", "CL", "CE", "R"];
options.forEach(option => {
const optionElement = document.createElement("option");
optionElement.value = option;
optionElement.innerHTML = option;
select.appendChild(optionElement);
});
cell.appendChild(select);
row.appendChild(cell);
}
}
timetable.appendChild(row);
}
function exportCSV() {
var rows = document.querySelectorAll("#timetable tr");
var csvData = [];
for (var i = 0; i < rows.length; i++) {
var rowData = [];
var cells = rows[i].querySelectorAll("td, th");
for (var j = 0; j < cells.length; j++) {
const select = cells[j].querySelector("select");
if(select){
rowData.push(select.value);
}else{
rowData.push(cells[j].innerText);
}
}
csvData.push(rowData);
}
var csv = Papa.unparse(csvData);
var csvData = new Blob([csv], {type: 'text/csv;charset=utf-8;'});
var csvURL = null;
if (navigator.msSaveBlob) {
csvURL = navigator.msSaveBlob(csvData, 'timetable.csv');
} else {
csvURL = window.URL.createObjectURL(csvData);
}
var tempLink = document.createElement('a');
tempLink.href = csvURL;
tempLink.setAttribute('download', 'timetable.csv');
tempLink.click();
// Convert the CSV data to a PDF and download it
var pdf = new jsPDF('l','mm','a4');
pdf.addPage();
pdf.text(csv, 10, 10);
pdf.save('timetable.pdf');
#timetable th {
border: 1px solid #ddd;
padding: 8px;
text-align: center;
background-color: #006699; /* bleu foncé /
}
#timetable tr:nth-child(even) {
background-color: #E6E6FA; / lavande */
}
/* Mise en page globale */
body {
background-color: #f1f1f1;
font-family: Arial, sans-serif;
margin: 0;
padding: 0;
}
/* Style de la barre de navigation */
nav {
background-color: #333;
color: #fff;
display: flex;
justify-content: space-between;
padding: 10px 20px;
}
nav a {
color: #fff;
text-decoration: none;
margin-right: 10px;
}
/* Style de la section principale */
main {
padding: 20px;
}
/* Style des titres */
h1, h2, h3 {
color: #333;
text-align: center;
margin-bottom: 20px;
}
/* Style des paragraphes */
p {
line-height: 1.5;
margin-bottom: 20px;
}
/* Style des images */
img {
max-width: 100%;
}
I see you already have pdfmaker available by your script so we can use that instead to convert your data to pdf with that instead.
You can achieve that with this download function:
function downloadPDFWithPDFMake() {
var rows = document.querySelectorAll("#timetable tr");
var data = [];
for (var i = 0; i < rows.length; i++) {
var rowData = [];
var cells = rows[i].querySelectorAll("td, th");
for (var j = 0; j < cells.length; j++) {
const select = cells[j].querySelector("select");
if(select){
rowData.push({text: select.value, style: 'tableData'});
}else{
rowData.push({text: cells[j].innerText, style: 'tableData'});
}
}
data.push(rowData);
}
var docDefinition = {
header: { text: 'Your awesome table', alignment: 'center' },
footer: function(currentPage, pageCount) { return ({ text: `Page ${currentPage} of ${pageCount}`, alignment: 'center' }); },
content: [
{
style: 'tableExample',
table: {
headerRows: 1,
body: [
...data
]
},
layout: {
fillColor: function(rowIndex) {
return (rowIndex % 2 === 0) ? '#E6E6FA' : null;
}
},
},
],
styles: {
tableExample: {
// table style
},
tableData: {
// table data style
},
},
};
pdfMake.createPdf(docDefinition).download('Your awesome table');
}
You have the hability to stylish on the configuration via the classes names. For a better info.

element switch class but don't get styles of the new class

I'm working on a real-life timetable where you can watch where the students current be. They have six meetings a day. if a student exit the scool i want to delete him from the list. if i doubleclick the name i want to change the class from name to selected and change the backgoundcolor so if i would press the "Schüler löschen"-button all selected get deleted.
Here is the code:
function createTable(){
var table = document.getElementById('table');
for(var j = 0;j<names.length;j++) {
var row = document.createElement("tr");
row.classList.add('row');
for(i=0;i<8;i++){
if(i==0){
var cell = document.createElement("input");
cell.classList.add('name');
cell.value= names[j];
cell.addEventListener("dblclick", function(){
alert(cell.classList);
cell.classList.add('selected');
alert(cell.classList);
});
}else if(i==4){
var cell = document.createElement("td");
cell.classList.add('spacer');
}else{
var cell = document.createElement("td");
cell.classList.add('cell');
cell.textContent = '';
}
row.appendChild(cell);
}
table.children[0].appendChild(row);
}
}
createTable();
the css:
input.name {
width: 20em;
background-color: #00ff00;
}
input.selected{
background-color: #ff7f7f;
}
The problem is if i double click the field the color dosent switch to red it stays green but the alert()-function shows that the class has switched
i've also tried
cell.name {
width: 20em;
background-color: #00ff00;
}
cell.selected{
background-color: #ff7f7f;
}
You need to remove cell class, and use this in that scope.
Try this:
function createTable() {
var table = document.getElementById('table');
var names = ["TEST 1", " TEST 2"];
for (var j = 0; j < names.length; j++) {
var row = document.createElement("tr");
row.classList.add('row');
for (i = 0; i < 8; i++) {
if (i == 0) {
var cell = document.createElement("input");
cell.classList.add('name');
cell.value = names[j];
cell.addEventListener("dblclick", function () {
alert(cell.classList);
this.classList.remove('cell');
this.classList.add('selected');
alert(cell.classList);
});
} else if (i == 4) {
var cell = document.createElement("td");
cell.classList.add('spacer');
} else {
var cell = document.createElement("td");
cell.classList.remove('selected');
cell.classList.add('cell');
cell.textContent = '';
}
row.appendChild(cell);
}
table.children[0].appendChild(row);
}
}
createTable();
input.name {
width: 20em;
background-color: #00ff00;
}
input.selected{
background-color: #ff7f7f;
}
<table id="table"><tbody></tbody></table>
I didn't get why cell is input element and why do you need to added in tr

Append table array value to another array

I have this code below that popups the cell value whenever the user clicks a specific cell.
What I'm currently trying to do is when the user clicks a cell i want that cell value to be appended to another column. I tried using the push method but it doesn't seem to be working. I'm not sure if I'm doing it the wrong way
JFiddle
HTML:
<table id="fruitsTable" class="fruitstableroni skillsTable class">
<thead></thead>
<tbody></tbody>
</table>
JavaScript:
var tbl = document.getElementById("fruitsTable");
if (tbl != null) {
for (var i = 0; i < tbl.rows.length; i++) {
for (var j = 0; j < tbl.rows[i].cells.length; j++)
tbl.rows[i].cells[j].onclick = function () {
obj[key2].push(this); //Trying to push it to the second column.
console.log(this);
};
}
}
function getval(cel) {
//console.log(cel.innerHTML);
}
var obj = {};
var key = "Red Fruits";
obj[key] = ['Apple', 'Cherry', 'Strawberry'];
var myArray = [];
myArray.push(obj);
var key2 = "Green Fruits";
obj[key2] = ['Watermelon', 'Durian', 'Avacado'];
var myArray2 = [];
myArray2.push(obj);
var key3 = "Random Fruits";
obj[key3] = ['Soursop', 'Papaya', 'Pineapple', 'Melon'];
var myArray3 = [];
myArray3.push(obj);
var $header = $("<tr>"),
cols = 0,
bodyString = "";
$.each(obj, function(key, values) {
cols = Math.max(cols, values.length); // find the longest
$header.append($('<th/>').text(key + ": " + values.length));
});
for (var i = 0; i < cols; i++) { // or use .map, but this is more undertandable for beginners
bodyString += '<tr>';
$.each(obj, function(key, values) {
bodyString += '<td>' +
(values[i] ? values[i] : "") + // ternary - instead of using if/else
'</td>';
});
bodyString += '</tr>';
}
$('.fruitsTableClass thead').html($header);
$('.fruitsTableClass tbody').html(bodyString);
var tbl = document.getElementById("fruitsTable");
if (tbl != null) {
for (var i = 0; i < tbl.rows.length; i++) {
for (var j = 0; j < tbl.rows[i].cells.length; j++)
tbl.rows[i].cells[j].onclick = function() {
getval(this);
obj[key2].push(this);
};
}
}
function getval(cel) {
alert(cel.innerHTML);
}
.class {
font-family: Open Sans;
}
.center {
display: flex;
justify-content: center
}
.skillsTable th {
border-left: 1px solid #AAA5A4;
border-right: 1px solid #AAA5A4;
}
table {
float: left;
border-collapse: collapse;
width: 70%
}
td {
border-left: 1px solid #AAA5A4;
border-right: 1px solid #AAA5A4;
padding-top: 8px;
padding-left: 11px;
font-size: 15px;
}
th {
color: #0080ff;
font-weight: normal;
border-bottom: 1px solid #AAA5A4;
padding-bottom: 5px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="center">
<table id="fruitsTable" class="fruitsTableClass skillsTable class">
<thead></thead>
<tbody></tbody>
</table>
</div>
Restructure your code to have a method to redraw UI and to enable event listeners:
function redraw (obj) {
var $header = $('<tr>'),
cols = 0,
bodyString = ''
$.each(obj, function (key, values) {
cols = Math.max(cols, values.length) // find the longest
$header.append($('<th/>').text(key + ': ' + values.length))
})
for (var i = 0; i < cols; i++) { // or use .map, but this is more undertandable for beginners
bodyString += '<tr>'
$.each(obj, function (key, values) {
bodyString += '<td>' +
(values[i] ? values[i] : '') + // ternary - instead of using if/else
'</td>'
})
bodyString += '</tr>'
}
$('.fruitsTableClass thead').html($header)
$('.fruitsTableClass tbody').html(bodyString)
}
function listener (obj) {
tbl = document.getElementById('fruitsTable')
if (tbl != null) {
for (var i = 0; i < tbl.rows.length; i++) {
for (var j = 0; j < tbl.rows[i].cells.length; j++)
tbl.rows[i].cells[j].onclick = function () {
getval(this)
obj[key2].push(this.innerHTML)
redraw(obj)
listener(obj)
};
}
}
}
function getval (cel) {
alert(cel.innerHTML)
}
redraw(obj)
listener(obj)
JSFiddle - https://jsfiddle.net/gnm8wv5f/
To add rows or cells to a table, you should use the methods insertRow() and insertCell().
Example, if you want to add a cell at the beginning of a row (from w3schools):
var row = document.getElementById("myRow");
var x = row.insertCell(0);
x.innerHTML = "New cell";
Or, to insert at the end:
var x = row.insertCell(row.cells.length);
Using cells.length you can find the number of cells in a particluar row, in that way you could know where to insert the new cell.
More info in: w3 | MDN
Try this code.
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
var daraArray=[];
$(document).ready(function(){
$(".classTd").click(function(){
//console.log($(this).html());
daraArray.push($(this).html());
console.log(daraArray);
});
});
</script>
<style type="text/css">
.classTd{
text-align: center;
}
</style>
</head>
<table id="fruitsTable" class="fruitstableroni skillsTable class" border="1">
<thead></thead>
<tbody>
<tr>
<td class="classTd" width="10%">1</td>
<td class="classTd" width="10%">2</td>
<td class="classTd" width="10%">3</td>
</tr>
<tr>
<td class="classTd" width="10%">4</td>
<td class="classTd" width="10%">5</td>
<td class="classTd" width="10%">6</td>
</tr>
<tr>
<td class="classTd" width="10%">7</td>
<td class="classTd" width="10%">8</td>
<td class="classTd" width="10%">9</td>
</tr>
</tbody>
</table>
</html>
The other answers here are good but you should definitely try AngularJs. The ng-repeat tag will easily cater your functionality.

How do I change an HTML table cell value by a dynamically added button in each row

var insert = document.getElementById('insertitem');
insert.addEventListener('click', function() {
var table = document.getElementById('insertfirsttable'),
itemType = prompt("Enter the Item type"),
filling1 = prompt("Enter the filling"),
filling2 = prompt("Enter the filling"),
filling3 = prompt("Enter the filling"),
stock = prompt("Enter the amount in stock"),
minimum_Stock = prompt("Enter the stock minimum");
for (var r = 0; r < 1; r += 1) {
var x = document.getElementById('insertfirsttable').insertRow(r);
for (var c = 0; c < 10; c += 1) {
var y = x.insertCell(c);
}
table.rows[r].cells[0].innerHTML = itemType;
table.rows[r].cells[1].innerHTML = filling1;
table.rows[r].cells[2].innerHTML = filling2;
table.rows[r].cells[3].innerHTML = filling3;
table.rows[r].cells[4].innerHTML = stock;
table.rows[r].cells[5].innerHTML = minimum_Stock;
table.rows[r].cells[9].style.width = "100px";
var CreateBtn = document.createElement("button");
CreateBtn.innerHTML = "sell";
CreateBtn.id = "sellbtn";
CreateBtn.style.width = "100px";
CreateBtn.style.height = "25px";
CreateBtn.style.cursor = "pointer";
CreateBtn.style.fontSize = "18px";
table.rows[r].cells[9].appendChild(CreateBtn);
var sellBtn = document.getElementById("sellbtn");
CreateBtn.onclick = function Sell() {
var sell = prompt("Enter the amount of stock you're selling");
for (var a = 0; a < table.length; a += 1) {
for (var b = 0; b < table.cells.length; b += 1) {
}
}
table.rows[a].cells[4].innerHTML = parseInt(table.rows[a].cells[4].innerHTML) - sell;
}
}
});
body {
margin: 0;
padding: 0;
background-color: #E6E6E6;
font-size: 20px;
}
table {
border-spacing: 1px;
width: 100%;
}
th {
padding: 1px;
}
#firsttablediv {
width: 100%;
}
#firsttable {
color: white;
background-color: green;
}
#insertitem {
width: 100%;
padding: 2px;
font-size: 20px;
cursor: pointer;
}
#insertfirsttable > tr {
background-color: #31B404;
}
<html>
<body>
<div id="firsttablediv">
<table id="firsttable" border="1">
<thead>
<th>Item Type</th>
<th colspan="3">Filling</th>
<th>Stock</th>
<th>Stock Minimum</th>
<th>Closing Inventory</th>
<th>Sell</th>
<th>Last Month Inventory</th>
<th colspan="2">
<button id="insertitem">New Item</button>
</th>
</thead>
<tbody id="insertfirsttable">
</tbody>
</table>
</div>
</body>
</html>
When I press on the sell button (which is dynamically added by JavaScript to each row when an item is added)
I want it to ask me about the amount I want to sell of that item and then when I enter the amount it should subtract the stock amount from the amount I want to sell (the one entered previously) and then update the stock amount in the cell of that item's row to the new number.
It's pretty simple but I just can't figure it out.
Change this line:
table.rows[a].cells[4].innerHTML = parseInt(table.rows[a].cells[4].innerHTML) - sell;
to this line:
this.parentNode.parentNode.cells[4].innerHTML = parseInt(this.parentNode.parentNode.cells[4].innerHTML) - sell;
To do it like you're trying, you would have to use a closure. This way, when you click a button, it adjusts the value of the button's parent's (td) parent (tr) cell 4.
Is that what you want? (fiddle)
var insert = document.getElementById('insertitem');
insert.addEventListener('click', function() {
var table = document.getElementById('insertfirsttable'),
itemType = prompt("Enter the Item type"),
filling1 = prompt("Enter the filling"),
filling2 = prompt("Enter the filling"),
filling3 = prompt("Enter the filling"),
stock = prompt("Enter the amount in stock"),
minimum_Stock = prompt("Enter the stock minimum");
for (var r = 0; r < 1; r += 1) {
var x = document.getElementById('insertfirsttable').insertRow(r);
for (var c = 0; c < 10; c += 1) {
var y = x.insertCell(c);
}
table.rows[r].cells[0].innerHTML = itemType;
table.rows[r].cells[1].innerHTML = filling1;
table.rows[r].cells[2].innerHTML = filling2;
table.rows[r].cells[3].innerHTML = filling3;
table.rows[r].cells[4].innerHTML = stock;
table.rows[r].cells[5].innerHTML = minimum_Stock;
table.rows[r].cells[9].style.width = "100px";
var CreateBtn = document.createElement("button");
CreateBtn.innerHTML = "sell";
CreateBtn.id = "sellbtn";
CreateBtn.style.width = "100px";
CreateBtn.style.height = "25px";
CreateBtn.style.cursor = "pointer";
CreateBtn.style.fontSize = "18px";
table.rows[r].cells[9].appendChild(CreateBtn);
var sellBtn = document.getElementById("sellbtn");
CreateBtn.onclick = function Sell() {
var sell = prompt("Enter the amount of stock you're selling");
for (var a = 0; a < table.length; a += 1) {
for (var b = 0; b < table.cells.length; b += 1) {
}
}
table.rows[a].cells[4].innerHTML = parseInt(table.rows[a].cells[4].innerHTML) - sell;
table.rows[a].cells[7].innerHTML = (parseInt(table.rows[a].cells[7].innerHTML)) ? parseInt(table.rows[a].cells[7].innerHTML) + parseInt(sell) : sell;
}
}
});
body {
margin: 0;
padding: 0;
background-color: #E6E6E6;
font-size: 20px;
}
table {
border-spacing: 1px;
width: 100%;
}
th {
padding: 1px;
}
#firsttablediv {
width: 100%;
}
#firsttable {
color: white;
background-color: green;
}
#insertitem {
width: 100%;
padding: 2px;
font-size: 20px;
cursor: pointer;
}
#insertfirsttable > tr {
background-color: #31B404;
}
<html>
<body>
<div id="firsttablediv">
<table id="firsttable" border="1">
<thead>
<th>Item Type</th>
<th colspan="3">Filling</th>
<th>Stock</th>
<th>Stock Minimum</th>
<th>Closing Inventory</th>
<th>Sell</th>
<th>Last Month Inventory</th>
<th colspan="2">
<button id="insertitem">New Item</button>
</th>
</thead>
<tbody id="insertfirsttable">
</tbody>
</table>
</div>
</body>
</html>
var rowCount =0; // add a counter for your row
var insert = document.getElementById('insertitem');
insert.addEventListener('click', function() {
rowCount++; // increase row counter
var table = document.getElementById('insertfirsttable'),
itemType = prompt("Enter the Item type"),
filling1 = prompt("Enter the filling"),
filling2 = prompt("Enter the filling"),
filling3 = prompt("Enter the filling"),
stock = prompt("Enter the amount in stock"),
minimum_Stock = prompt("Enter the stock minimum");
for (var r = 0; r < 1; r += 1) {
var x = document.getElementById('insertfirsttable').insertRow(r);
for (var c = 0; c < 10; c += 1) {
var y = x.insertCell(c);
}
table.rows[r].cells[0].innerHTML = itemType;
table.rows[r].cells[1].innerHTML = filling1;
table.rows[r].cells[2].innerHTML = filling2;
table.rows[r].cells[3].innerHTML = filling3;
table.rows[r].cells[4].innerHTML = stock;
table.rows[r].cells[4].id = "stock_"+rowCount; // add an id to your cell
table.rows[r].cells[5].innerHTML = minimum_Stock;
table.rows[r].cells[7].id = "sell_"+rowCount;
table.rows[r].cells[7].innerHTML = "0";
table.rows[r].cells[9].style.width = "100px";
var CreateBtn = document.createElement("button");
CreateBtn.innerHTML = "sell";
CreateBtn.id = "sellbtn";
CreateBtn.title = rowCount; // add title to your button to have the row counter
CreateBtn.style.width = "100px";
CreateBtn.style.height = "25px";
CreateBtn.style.cursor = "pointer";
CreateBtn.style.fontSize = "18px";
table.rows[r].cells[9].appendChild(CreateBtn);
var sellBtn = document.getElementById("sellbtn");
CreateBtn.onclick = function Sell() {
var sell = prompt("Enter the amount of stock you're selling");
stock_cell = document.getElementById("stock_"+this.title); // find the stock cell with row counter
sell_cell = document.getElementById("sell_"+this.title);
stock_item = parseInt(stock_cell.innerHTML); // get the current value
sell_item = parseInt(sell_cell.innerHTML);
stock_cell.innerHTML = stock_item - parseInt(sell); // increase sell item from stock
sell_cell.innerHTML = sell_item + parseInt(sell);
}
}

Create Table Confusion

I am having some issues / confusion and I am stuck as to where to go from here.
I am experimenting with using Javascript to create tables for my data, and then to display them in HTML. I have created the HTML table without a drama, but the JS one I am having trouble with.
Here is a picture of my expected output:
from here, I have the following code to draw the table. However, I can only get up to the 7th row before I get stuck on how to finish the table.
I have read a lot of references and I can not figure out how to do it!
Here is my code so far:
function drawTable3() {
var input = document.createElement("input");
var tr = document.createElement("tr");
var td = document.createElement("td");
var div = document.getElementById("dropper")
//create table
var drawTable = document.createElement("table");
drawTable.id = "dropperTable";
drawTable.className = "tg";
div.appendChild(drawTable);
var table = document.getElementById("dropperTable");
var input = document.createElement("input");
input.id = "D" + [i] + "Size";
input.type = "number";
//Create Head Elements
for ( var i = 0; i < 3; i++ ) {
var createHead = document.createElement("th");
if ( i == 0) {
createHead.innerHTML = "";
} else if ( i == 1) {
createHead.innerHTML = "Dropper Duct Size";
} else if ( i == 2) {
createHead.innerHTML = "Dropper Duct Capacity";
}
table.appendChild(createHead);
}
for ( var i = 1; i < 7 ; i++ ) {
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
var cell1 = row.insertCell(0);
var dropperName = document.createElement("output");
dropperName.id = "D" + [i] + "Size";
dropperName.innerHTML = "Dropper Duct Side " + [i];
cell1.appendChild(dropperName);
var cell2 = row.insertCell(1);
var dropperInput = document.createElement("input");
dropperInput.type = "number";
dropperInput.id = "D" + [i] + "Capacity";
cell2.appendChild(dropperInput);
var cell3 = row.insertCell(2);
var dropperOutput = document.createElement("output");
dropperOutput.id = "D" + [i] + "Capacity";
cell3.appendChild(dropperOutput);
}
}
drawTable3();
.tg {
border-collapse:collapse;
border-spacing:0;
text-align: center;
}
.tg td{
font-family:Arial, sans-serif;
font-size:14px;
font-weight:normal;
padding:10px 5px;
border-style:solid;
border-width:1px;
overflow:hidden;
word-break:normal;
text-align: center;
}
.tg th{
font-family:Arial, sans-serif;
font-size:14px;
font-weight:normal;
padding:10px 5px;
border-style:solid;
border-width:1px;
overflow:hidden;
word-break:normal;
text-align: center;
vertical-align: top;
}
.tg .tg-s6z2{
text-align:center
}
.smallInput {
width: 50px;
text-align: center;
}
.roomIdent {
}
.factors {
text-align: center;
width: 80px;
}
.factors2 {
text-align: center;
width: 150px;
}
.tg2 {
border-top-style: none;
border-right-style: none;
border-bottom-style: none;
border-left-style: none;
border-top-color: #FFF;
border-right-color: #FFF;
border-bottom-color: #FFF;
border-left-color: #FFF;
}
<div id="dropper"></div>
Some comments on your code:
function drawTable3() {
var input = document.createElement("input");
var tr = document.createElement("tr");
var td = document.createElement("td");
tr and td aren't used anywhere, input is re–initialised later.
var div = document.getElementById("dropper")
//create table
var drawTable = document.createElement("table");
drawTable.id = "dropperTable";
drawTable.className = "tg";
div.appendChild(drawTable);
var table = document.getElementById("dropperTable");
You already have a reference to the table as drawTable, so why not call it table from the start? Anyway, the above is equivalent to:
var table = drawTable;
.
var input = document.createElement("input");
You already created an input above and assigned it to input, this replaces it with another input.
input.id = "D" + [i] + "Size";
i hasn't been assigned a value yet (it's declared lower down so it exists as a variable), so its value is undefined. The expression [i] will create the array [undefined] that is then converted to a string because of the + operators and other values in the expression being strings, returning an empty string. So the ID assigned is:
'DSize'
.
input.type = "number";
//Create Head Elements
for ( var i = 0; i < 3; i++ ) {
var createHead = document.createElement("th");
if ( i == 0) {
createHead.innerHTML = "";
} else if ( i == 1) {
createHead.innerHTML = "Dropper Duct Size";
} else if ( i == 2) {
createHead.innerHTML = "Dropper Duct Capacity";
}
table.appendChild(createHead);
}
The above could be a bit more concise if you use an array for the values and assign them based on the value if i. Also, if you are just setting a text value, probably better to insert a text node:
var headCellValues = ['','Dropper Duct Size','Dropper Duct Capacity'];
for ( var i = 0; i < 3; i++ ) {
var createHead = document.createElement("th");
createHead.appendChild(document.createTextNode(headCellValues[i]));
table.appendChild(createHead);
}
.
for ( var i = 1; i < 7 ; i++ ) {
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
This seems to be the only place that rowCount is used. To append a row using insertRow, provide a value of -1:
var row = table.insertRow(-1);
.
var cell1 = row.insertCell(0);
var dropperName = document.createElement("output");
dropperName.id = "D" + [i] + "Size";
Here again, [1] creates an array that is then converted to a string. Just use i to get say "D0Size":
dropperName.id = "D" + i + "Size";
.
dropperName.innerHTML = "Dropper Duct Side " + [i];
Same here, use:
dropperName.innerHTML = "Dropper Duct Side " + i;
dropperName.appendChild(document.createTextNode("Dropper Duct Side " + i));
The same should be applied to the rest of the code. You might consider cloning entire rows as it's faster than creating all the elements one by one, or making separate functions to create each type of row. It seems that the header and footer parts can be HTML, and only the intervening rows need to be dynamically created.
cell1.appendChild(dropperName);
var cell2 = row.insertCell(1);
var dropperInput = document.createElement("input");
dropperInput.type = "number";
dropperInput.id = "D" + [i] + "Capacity";
cell2.appendChild(dropperInput);
var cell3 = row.insertCell(2);
var dropperOutput = document.createElement("output");
dropperOutput.id = "D" + [i] + "Capacity";
cell3.appendChild(dropperOutput);
}
}
drawTable3();

Categories