I want to have first element of my row as <th> I am doing this but I am getting <td> as my first element. What I am doing wrong?
Basically I want something like this <tr><th><b>Table Header</b></th><td>item1</td><td>item2</td><\tr>
var table = document.getElementById("data");
var row = table.insertRow(-1);
var cell1 = row.insertCell(0);
$("#table td:first").append('<th><b>Table Header</b></th>');
You just need to not use insertCell in your question
var table = document.getElementById("data");
var row = table.insertRow(-1);
$(row).append('<th>Table Header</th>');
<table id="data"></table>
<script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script>
You can create your own method to insert a <th>
// insert <TH> method, at your oxn risk
HTMLTableRowElement.prototype.insert_th_Cell = function(index)
{
let cell = this.insertCell(index)
, c_th = document.createElement('th')
cell.replaceWith(c_th)
return c_th
}
//---------------------------------------
let thead = myTable.createTHead()
, tBody = myTable.createTBody()
, rowHead = thead.insertRow()
;
rowHead.insertCell()
rowHead.insert_th_Cell().textContent = 'c1'
rowHead.insert_th_Cell().textContent = 'c2'
rowHead.insert_th_Cell().textContent = 'c3'
let nRow = tBody.insertRow()
nRow.insert_th_Cell().textContent = 'line'
nRow.insertCell().textContent = 'AA'
nRow.insertCell().textContent = 'BB'
nRow.insertCell().textContent = 'CC'
table {
border-collapse : collapse;
margin : 2em 1em;
}
td,th {
padding : .2em .8em;
border : 1px solid darkblue;
}
thead {
background-color: aquamarine;
}
tbody th{
background-color: orchid;
}
<table id="myTable"></table>
Related
Using a javascript function
function initializeUserTable(tableHeaders , tableData ) {
// I want to set table headers and table data
}
var tableHeaders = "ID,USERNAME,STATUS,LOGIN";
var tableData = "1,ABC,ACTIVE,N,2,DEF,INACTIVE,Y,3,XYZ,ACTIVE,Y";
want to set the tableHeaders as a header and data as a tableData, so the table looks like
I hope this is help you
var table = document.getElementsByTagName("table")[0];
var ths = ["ID","USERNAME","STATUS","LOGIN"];
var tds = [["1","ABC","ACTIVE","N"],["2","DEF","INACTIVE","Y"],["3","XYZ","ACTIVE","Y"]];
let tr = document.createElement("tr");
function initializeUserTable(tableHeaders , tableData ){
for(let i=0;i<ths.length;i++){
for(let j=0;j<tableHeaders.length;j++){
if(i==0){
let th = document.createElement("th");
th.innerHTML=tableHeaders[j];
if(j==0){
tr.appendChild(th);
}
tr.appendChild(th);
}
else{
let td = document.createElement("td");
td.innerHTML=tableData[i-1][j];
tr.appendChild(td);
}
}
table.insertAdjacentElement("beforeend",tr);
tr = document.createElement("tr");
}
}
initializeUserTable(ths,tds);
table{
border-collapse: collapse;
}
table,th, td {
border:2px solid black;
width:50%;
height:20px;
text-align: center;
}
th{
background: lightgray;
}
<!DOCTYPE html>
<html>
<head>
<title>tableData</title>
</head>
<body>
<table>
</table>
</body>
</html>
you can use :
yourstring.split(",") to transform your data as array
table.insertRow to insert new row in a table tag
row.insertCell to insert new cell in table tag
var tableHeaders = "ID,USERNAME,STATUS,LOGIN";
var tableData = "1,ABC,ACTIVE,N,2,DEF,INACTIVE,Y,3,XYZ,ACTIVE,Y";
function insertRow(table) {
if (!table.dataset.number) {
table.dataset.number = 0;
}
var rowNumber = parseInt(table.dataset.number);
table.dataset.number = rowNumber + 1;
return table.insertRow(rowNumber);
}
function insertCell(row) {
if (!row.dataset.number) {
row.dataset.number = 0;
}
var cellNumber = parseInt(row.dataset.number);
row.dataset.number = cellNumber + 1;
return row.insertCell(cellNumber);
}
function initializeUserTable(tableHeaders, tableData) {
var headers = tableHeaders.split(",");
var datas = tableData.split(",");
var table = document.getElementById('my-table');
var row = insertRow(table);
let cell;
headers.forEach(header => {
cell = insertCell(row);
cell.outerHTML = `<th>${header}</th>`;
});
row = insertRow(table);
datas.forEach(data => {
cell = insertCell(row);
cell.innerHTML = data;
if (parseInt(row.dataset.number) === headers.length) {
row = insertRow(table);
}
});
}
initializeUserTable(tableHeaders, tableData);
table,th, td {
border:1px solid #ddd;
padding:5px;
text-align: center;
}
table {
border-collapse: collapse;
}
th {
background: #efefef;
}
<table id="my-table"><table>
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>
I have a table that is created by javascript when it obtains data from the data base, this is the function
function gotCData(snapshot){
snapshot.forEach(userSnapshot => {
var confirmed = userSnapshot.val().confirmed;
var date = userSnapshot.val().date;
var deaths = userSnapshot.val().deaths;
var recovered = userSnapshot.val().recovered;
//console.log(confirmed, date, deaths, recovered);
var local = k;
var csvDate = date;
var population = recovered;
var totalCases = confirmed;
var totalDeaths = deaths;
//console.log(location);
var tr = document.createElement('tr');
var td1 = document.createElement('td');
var td2 = document.createElement('td');
var td3 = document.createElement('td');
var td4 = document.createElement('td');
var td5 = document.createElement('td');
var tdLocal = document.createTextNode(local);
var tdPopulation = document.createTextNode(population);
var tdTotalCases = document.createTextNode(totalCases);
var tdTotalDeaths = document.createTextNode(totalDeaths);
var tdDate = document.createTextNode(csvDate);
td1.appendChild(tdLocal)
td2.appendChild(tdPopulation)
td3.appendChild(tdTotalCases)
td4.appendChild(tdTotalDeaths)
td5.appendChild(tdDate)
var tRow1 = document.getElementById("displayCorona").appendChild(td1);
var tRow2 = document.getElementById("displayCorona").appendChild(td2);
var tRow3 = document.getElementById("displayCorona").appendChild(td3);
var tRow4 = document.getElementById("displayCorona").appendChild(td4);
var tRow5 = document.getElementById("displayCorona").appendChild(td5);
//Writes the Table Row then the Divs after
document.getElementById("displayCorona").appendChild(tr, tRow1, tRow2, tRow3, tRow4, tRow5);
});
}
I have a search function :
function search(){
// Declare variables
var input, filter, table, tr, td, i, txtValue;
input = document.getElementById("myInput");
filter = input.value.toUpperCase();
table = document.getElementById("displayCorona");
tr = table.getElementsByTagName("tr");
// Loop through all table rows, and hide those who don't match the search query
for (i = 0; i < tr.length; i++) {
td = tr[i].getElementsByTagName("td1")[0];
if (td) {
txtValue = td.textContent || td.innerText;
if (txtValue.toUpperCase().indexOf(filter) > -1) {
tr[i].style.display = "";
} else {
tr[i].style.display = "none";
}
}
}
}
The tables are created when I loop through each node in a Firebase database. The search function is from W3Schools but im not sure why it is not searching the table that is created by the above function.
Here's some code for you to look at.
"use strict";
function newEl(tag){return document.createElement(tag)}
function byId(id){return document.getElementById(id)}
window.addEventListener('load', onLoad, false);
function onLoad(evt)
{
var inputStr = "I have a table that is created by javascript when it obtains data from the data base, this is the function";
document.body.appendChild( makeTable(inputStr) );
byId('goBtn').addEventListener('click', onGoBtn, false);
}
function makeTable(input)
{
let tbl = newEl('table');
input = input.replace(',', '');
let words = input.split(' ');
let nWords = words.length;
let nRows = parseInt(nWords/5) + nWords%5;
for (var j=0; j<nRows; j++)
{
let tr = newEl('tr');
for (var col=0; col<5; col++)
{
let td = newEl('td');
td.textContent = words[j*5 + col];
tr.appendChild(td);
}
tbl.appendChild(tr);
}
return tbl;
}
function highlightContainingCells(input, highlightClassname)
{
let cells = document.querySelectorAll('td');
cells.forEach( cellFunc );
function cellFunc(curCell)
{
if (input == curCell.textContent)
curCell.classList.add(highlightClassname);
else
curCell.classList.remove(highlightClassname);
}
}
function onGoBtn(evt)
{
let str = byId('searchStr').value;
highlightContainingCells(str, "found");
}
td
{
color: #333;
background-color: #ddd;
}
td.found
{
color: #ddd;
background-color: #333;
}
<input id='searchStr' value='javascript'/><button id='goBtn'>SEARCH</button></br>
There were so many wrong things.
You had not specified what data type snapshot is. Is it array or something else? I assumed it to be array of JSON objects, where each object denotes a row in your table.
I did not understand the use of .val() method. I removed it completely.
The table being generates was not in correct format. You were appending tr to table. But instead of appending td to tr you were also appending them to table. I have corrected that also.
There was an undefined variable k which was being used to set local.
display:block style on tr was displaying table in a weird way once rows are eliminated. I changed it to display:table-row instead, which is ideal for table-rows
function gotCData(snapshot) {
snapshot.forEach(userSnapshot => {
var confirmed = userSnapshot.val().confirmed;
var date = userSnapshot.val().date;
var deaths = userSnapshot.val().deaths;
var recovered = userSnapshot.val().recovered;
var local = userSnapshot.local; // we will look at this later
// console.log(confirmed, date, deaths, recovered);
// var local = k;
var csvDate = date;
var population = recovered;
var totalCases = confirmed;
var totalDeaths = deaths;
//console.log(location);
var tr = document.createElement('tr');
var td1 = document.createElement('td');
var td2 = document.createElement('td');
var td3 = document.createElement('td');
var td4 = document.createElement('td');
var td5 = document.createElement('td');
var tdLocal = document.createTextNode(local);
var tdPopulation = document.createTextNode(population);
var tdTotalCases = document.createTextNode(totalCases);
var tdTotalDeaths = document.createTextNode(totalDeaths);
var tdDate = document.createTextNode(csvDate);
td1.appendChild(tdLocal)
td2.appendChild(tdPopulation)
td3.appendChild(tdTotalCases)
td4.appendChild(tdTotalDeaths)
td5.appendChild(tdDate)
tr.appendChild(td1)
tr.appendChild(td2)
tr.appendChild(td3)
tr.appendChild(td4)
tr.appendChild(td5)
// Writes the Table Row then the Divs after
document.getElementById("displayCorona").appendChild(tr);
});
}
function search() {
// Declare variables
var input, filter, table, tr, td, i, txtValue;
input = document.getElementById("myInput");
filter = input.value.toUpperCase();
table = document.getElementById("displayCorona");
tr = table.querySelectorAll("tr:not(.table-head)");
// Loop through all table rows, and hide those who don't match the search query
var found
for (i = 0; i < tr.length; i++) {
tds = tr[i].getElementsByTagName("td")
if (tds) {
found = false
for (j = 0; j < tds.length && found == false; j++) {
td = tds[j];
txtValue = td.textContent || td.innerText;
if (txtValue.toUpperCase().indexOf(filter) > -1) {
tr[i].style.display = "table-row";
found = true
break
}
}
if (found == false) tr[i].style.display = "none";
}
}
}
// This is used for testing only
// window.onload = () => {
// snapshot = firebaseToArray(firebaseJSON)
// gotCData(snapshot)
// }
table {
font-family: arial, sans-serif;
border-collapse: collapse;
width: 100%;
margin-top: 20px;
}
td, th {
border: 1px solid #dddddd;
text-align: left;
padding: 8px;
}
tr:nth-child(even) {
background-color: #dddddd;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<input type="text" id="myInput">
<button type="submit" onclick="search()">Search</button>
<table id="displayCorona">
<tr class="table-head">
<th>Location</th>
<th>Population</th>
<th>Total cases</th>
<th>Total deaths</th>
<th>Date</th>
</tr>
</table>
</body>
</html>
Some friendly advice:
I see you have extracted data from snapshot and assign them twice to variables, for say you first extract date from snapshot and then assign it to csvDate, while you could directly extract date to csvDate
You were creating text nodes for td, assigning them values and appending them to corresponding td node. You could directly insert data using innerHTML or innerText for example, td1.innerText = local. No need to create textNodes and append them!
It seems like you directly copy-pasted code for search function from w3schools. Please review such codes after using.
Use developer console to find common errors. Debugging your code can solves many common problems, so get familiar with it.
Hello i am trying to append some strings from an array to an table. I want every array item to have its own tr element.
The things i have tried so far is this:
const body = document.body
const table = document.createElement('table')
const tr = document.createElement('tr')
const th = document.createElement('th')
const form = document.createElement('form')
const label = document.createElement('label')
table.innerHTML
body.append(table)
tr.innerHTML
table.append(tr)
const thText = ["ID", "First name", "Last name", "Email", "Phone number", "Actions"]
thText.forEach((text)=>{
th.innerHTML = text
tr.append(th);
})
When console.log(th) i get <th> Actions </th> 6 times. but the only thing that is rendered is Actions once.
Would love to get some help. Thanks :)
You're only creating one th element. You'd need to create one for each iteration, so, within the loop:
thText.forEach(text => {
const th = document.createElement('th')
th.innerHTML = text
tr.append(th)
})
There's a few different ways to do this. Here's an example of one way. This method does a few things differently then your example.
It creates and uses a thead element for proper table formatting.
It uses a basic for loop method.
It creates a new th element for each header label in the array, then it appends it to the tr element.
It uses textContent instead of innerHTML
const headerLabels = ["ID", "First name", "Last name", "Email", "Phone number", "Actions"]
const body = document.body
const table = document.createElement('table')
const thead = document.createElement('thead')
const tr = document.createElement('tr')
thead.append(tr)
table.append(thead)
body.append(table)
for (let i = 0; i < headerLabels.length; i++) {
let th = document.createElement('th')
th.textContent=headerLabels[i]
tr.append(th)
}
td, th {
border: 1px solid #ddd;
padding: 8px;
}
tr:nth-child(even) {
background-color: #f2f2f2;
}
th {
padding-top: 12px;
padding-bottom: 12px;
text-align: left;
background-color: #4CAF50;
color: white;
}
<body>
<script src="main.js"></script>
</body>
I'm trying to use JavaScript to take something like this:
<div class="content">Fruit<br>
Apple: 100 - 250<br>
Orange: 90 - 190<br>
Pear: 140 - 230<br>
Melon: 1000 - 1280</div>
And put it into a table like this:
table {
border-collapse: collapse;
}
table, th, td {
border: 1px solid black;
}
<table><tr><th>Fruit</th><th>Min</th><th>Max</th><th>Difference</th></tr><tr><td>Apple</td><td>100</td><td>250</td><td>150</td></tr><tr><td>Orange</td><td>90</td><td>190</td><td>100</td></tr><tr><td>Pear</td><td>140</td><td>230</td><td>90</td></tr><tr><td>Melon</td><td>1000</td><td>1280</td><td>280</td></tr></table>
I'm having trouble finding a place to start.
The following code creates a table based on the content from the div "content" when the user clicks the button.
(function(){
var content = document.getElementById("content");
var tresult = document.getElementById("tresult");
var btnCreateTable = document.getElementById("btnCreateTable");
//adds event listener to button
btnCreateTable.addEventListener('click',function(e){
//parse and create table
parseContent(content);
});
function parseContent(oCon){
var nodes = content.innerText;
var sNodes = nodes.split("\n");
var newTable = "";
var table = document.createElement('table');
//sColumns is used to def the columns for the table
var sColumns = [
"Fruit",
"Min",
"Max",
"Difference"
];
var table = document.createElement('table');
var tr = document.createElement('tr');
for(a = 0; a < sColumns.length; a++){
var th = document.createElement('th');
th.innerText = sColumns[a];
tr.appendChild(th);
}
table.appendChild(tr);
var oFruit = [],
oMin = [],
oMax = [],
oNumbers = [];
for(b = 1; b < sNodes.length; b++){
var sFruit = sNodes[b].split(":");
for(c = 0; c < sFruit.length; c++){
if(c % 2 === 0){
oFruit.push(sFruit[c]);
}else{
oNumbers.push(sFruit[c]);
}
}
}
for(var d = 0; d < oNumbers.length; d++){
var spNum = oNumbers[d].split("-");
oMin.push(spNum[0]);
oMax.push(spNum[1]);
}
for(var f = 0; f < sNodes.length - 1; f++){
var tr2 = document.createElement('tr');
var td = document.createElement('td');
td.innerText = oFruit[f];
tr2.appendChild(td);
td = document.createElement('td');
td.innerText = oMin[f];
tr2.appendChild(td);
td = document.createElement('td');
td.innerText = oMax[f];
tr2.appendChild(td);
td = document.createElement('td');
td.innerText = oMax[f] - oMin[f];
tr2.appendChild(td);
table.appendChild(tr2);
}
tresult.appendChild(table);
};
}());
table {
border-collapse: collapse;
}
table, th, td {
border: 1px solid black;
}
<!DOCTYPE html>
<html lang="en">
<head>
<title></title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<div id="content" class="content">Fruit<br>
Apple: 100 - 250<br>
Orange: 90 - 190<br>
Pear: 140 - 230<br>
Melon: 1000 - 1280
</div>
<div id="tresult"></div>
<button id="btnCreateTable">Create table</button>
</body>
</html>
This is too hard coded but you can use as a base.
var myControl = $('.content');
var inputData = myControl.text().split('\n');
$('.content').remove();
var table = "<table><tr><th>" + inputData[0] + "</th><th>Min</th><th>Max</th><th>Difference</th></tr>";
for (var i = 1; i < inputData.length; i++)
{
var cells = inputData[i].replace(': ', ' ').replace(' - ',' ').split(' ');
table += "<tr><th>"+cells[0]+"</th><th>"+cells[1]+"</th><th>"+ +cells[2] +"</th><th>"+ (parseInt(cells[2]) - parseInt(cells[1])) +"</th></tr>"
};
table+="</table>"
$("body").append(table);
table {
border-collapse: collapse;
}
table, th, td {
border: 1px solid black;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<div class="content">Fruit<br>
Apple: 100 - 250<br>
Orange: 90 - 190<br>
Pear: 140 - 230<br>
Melon: 1000 - 1280</div>