Adding a new column to html table using javascript - javascript

So i have scared some data and saved it on to a CSV file. I am not trying to present this data on to a html page. Since the data saved has only two columns(Item name and Price), it is only displaying those two columns.
I want to add another column next to it, so i can have a "Add to basket" button inside it. I am not sure how i am able to add a new column here.
Can anyone help please? Thank you
<body>
<!-- Header-->
<div id="header">
<button type="button" class="button">Basket</button>
</div>
<!-- CSV FILE DATA WILL APPEAR HERE-->
<div class="container">
<div class="table-responsive">
<div id="order_list"><p id="tableintro"> Choose your desired supermarket</p>
</div>
</div>
</div>
<!--THIS BUTTON WILL LOAD DATA FROM CSV FILE-->
<div id="sidebar">
<div align="center">
<button type="button" name="load_data" id="load_data" class="btn btn-info">Tesco Brent Cross</button>
</div>
</div>
<!--Javascript code for Tesco-->
<script>
$(document).ready(function(){
$('#load_data').click(function(){
$.ajax({
url:"Tesco.csv",
dataType:"text",
success:function(data)
{
var tesco_data = data.split(/\r?\n|\r/);
var table_data = '<table class="table table-bordered table-striped">';
for(var count = 0; count<tesco_data.length; count++)
{
var cell_data = tesco_data[count].split(",");
table_data += '<tr>';
for(var cell_count=0; cell_count<cell_data.length; cell_count++)
{
if(count === 0)
{
table_data += '<th>'+cell_data[cell_count]+'</th>';
}
else
{
table_data += '<td>'+cell_data[cell_count]+'</td>';
}
}
table_data += '</tr>';
}
table_data += '</table>';
$('#order_list').html(table_data);
}
});
});
});
</script>

You have a formatting issue mounting your table. If you only have two cells per row in this case, a second for loop seems like an overkill. Try replacing your for loop with this one instead:
for (var count = 0; count < tesco_data.length; count++)
{
var cell_data = tesco_data[count].split(",");
var name = cell_data[0];
var price = cell_data[1];
if (count === 0)
{
table_data += '<tr><th>' + name + '</th><th>' + price + '</th><th>action</th></tr>';
continue;
}
table_data += '<tr><td>' + name + '</td><td>' + price + '</td><td><button type="button">Add to cart</button></td></tr>';
}

Related

How to Highlight row based on particular value in the table?

I'm working on a YouTube tutorial that works on Google App Script and Google Sheets
I want to highlight the row if it contains the value "ABSENT", I tried many ways to but ended in failures,
Need some assistance to modify this code to do the job
NOTE: Updated the code for better understanding.
CODE.JS
function doGet(e) {
return HtmlService.createTemplateFromFile("Index").evaluate()
.setTitle("WebApp: Search By Password")
.addMetaTag('viewport', 'width=device-width, initial-scale=1')
.setXFrameOptionsMode(HtmlService.XFrameOptionsMode.ALLOWALL);
}
/* PROCESS FORM */
function processForm(formObject){
var concat = formObject.searchtext+formObject.searchtext2;
var result = "";
if(concat){//Execute if form passes search text
result = search(concat);
}
return result;
}
//SEARCH FOR MATCHED CONTENTS ;
function search(searchtext){
var spreadsheetId = '1bahNEJIweyuvmocYbSR8Nc_IA_HP3qdO7tCKU6w'; //** CHANGE !!!!
var sheetName = "Data"
var range = SpreadsheetApp.openById(spreadsheetId).getSheetByName(sheetName).getDataRange();
var data = range.getDisplayValues();
var ar = [];
data.forEach(function(f) {
if (~[f[8]].indexOf(searchtext)) {
ar.push([ f[2],f[3],f[4],f[5],f[6],f[7] ]);
}
});
return ar;
};
INDEX.HMLT
<!DOCTYPE html>
<html>
<head>
<base target="_self">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap#4.5.3/dist/css/bootstrap.min.css" integrity="sha384-TX8t27EcRE3e/ihU7zmQxVncDAy5uIKz4rEkgIXeMed4M0jlfIDPvg6uqKI2xXr2" crossorigin="anonymous">
<style>
/* h5 {background: red;} */
</style>
</head>
<body>
<div class="container">
<br>
<div class="row">
<div class="col">
<!-- ## SEARCH FORM ------------------------------------------------ -->
<center><form id="search-form" onsubmit="handleFormSubmit(this)">
<div class="form-group mb-2">
<h5 for="searchtext">Work Log Records</h5>
</div><p>
<div class="form-group mx-sm-3 mb-3">
<input type="email" class="form-control col-sm-6" id="searchtext" name="searchtext" placeholder="Email" required><br>
<input type="text" class="form-control col-sm-6" id="searchtext2" name="searchtext2" placeholder="Employee ID" required>
</div><p>
<button type="submit" class="btn btn-primary mb-2" >Generate
<span id="resp-spinner5" class="spinner-border spinner-border-sm d-none" role="status" aria-hidden="true"></span>
</button>
</form></center>
<!-- ## SEARCH FORM ~ END ------------------------------------------- -->
</div>
</div>
<div class="row">
<div class="col">
<!-- ## TABLE OF SEARCH RESULTS ------------------------------------------------ -->
<div id="search-results" class="table table-responsive ">
<!-- The Data Table is inserted here by JavaScript -->
</div>
<!-- ## TABLE OF SEARCH RESULTS ~ END ------------------------------------------------ -->
</div>
</div>
</div>
<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js#1.16.1/dist/umd/popper.min.js" integrity="sha384-9/reFTGAW83EW2RDu2S0VKaIzap3H66lZH81PoYlFhbGU+6BZp6G7niu735Sk7lN" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap#4.5.3/dist/js/bootstrap.min.js" integrity="sha384-w1Q4orYjBQndcko6MimVbzY0tgp4pWB4lZ7lr30WKz0vr/aWKhXdBNmNb5D92v7s" crossorigin="anonymous"></script>
<!--##JAVASCRIPT FUNCTIONS ---------------------------------------------------- -->
<script>
//PREVENT FORMS FROM SUBMITTING / PREVENT DEFAULT BEHAVIOUR
function preventFormSubmit() {
var forms = document.querySelectorAll('form');
for (var i = 0; i < forms.length; i++) {
forms[i].addEventListener('submit', function(event) {
event.preventDefault();
});
}
}
window.addEventListener("load", preventFormSubmit, true);
//HANDLE FORM SUBMISSION
function handleFormSubmit(formObject) {
if(document.getElementById('searchtext').value == "" || document.getElementById('searchtext2').value == ""){
alert("Fill in Email and Employee ID");
}else{
document.getElementById('resp-spinner5').classList.remove("d-none");
google.script.run.withSuccessHandler(createTable).processForm(formObject);
document.getElementById("search-form").reset();
};
};
//CREATE THE DATA TABLE
function createTable(dataArray) {
document.getElementById('resp-spinner5').classList.add("d-none");
if(dataArray && dataArray !== undefined && dataArray.length != 0){
var result = "<table class='table table-sm table-dark table-hover' id='dtable' style='font-size:0.8em'>"+
"<thead style='white-space: nowrap'>"+
"<tr >"+ //Change table headings to match with the Google Sheet
"<th scope='col'>EMPLOYEE</th>"+
"<th scope='col'>DATE</th>"+
"<th scope='col'>IN TIME</th>"+
"<th scope='col'>OUT TIME</th>"+
"<th scope='col'>HOURS</th>"+
"<th scope='col'>STATUS</th>"+
"</tr>"+
"</thead>";
for(var i=0; i<dataArray.length; i++) {
result += "<tr>";
for(var j=0; j<dataArray[i].length; j++){
result += "<td>"+dataArray[i][j]+"</td>";
}
result += "</tr>";
}
result += "</table>";
var div = document.getElementById('search-results');
div.innerHTML = result;
}else{
var div = document.getElementById('search-results');
//div.empty()
div.innerHTML = "Data not found!";
}
}
</script>
<!--##JAVASCRIPT FUNCTIONS ~ END ---------------------------------------------------- -->
</body>
</html>
I guess dataArray[i][j] is where "Absent" can be.
In this case, you are basically looking for an existence of a string("Absent") inside another string(dataArray[i][j])
thats where you use search() method.
https://www.w3schools.com/jsref/jsref_search.asp
Some code as below will work.
if (dataArray[i][j].search("ABSENT") > -1){
/*change color to red or whatever*/
}
As far as I can tell given code has nothing to do with Google Spreadsheet. It looks like some Javascript code that makes an HTML-table for a web browser.
But how exactly this HTML-table will get into Google Spreadsheet? Manually via copy and paste?
Since they can be two very different task:
-- to change color of cells in the original HTML-table (but the colors may disappear after putting it on Google Spreadsheet via system clipboard).
-- to change color of cells in Google Spreadsheet table (but firstly the table should to get there somehow, how?).
I believe your goal as follows.
You want to set the background color of the row when the row has the value of ABSENT.
In this case, how about checking whether the value of ABSENT is included in each row? When this is reflected to your script, it becomes as follows.
From:
for(var i=0; i<dataArray.length; i++) {
result += "<tr>";
for(var j=0; j<dataArray[i].length; j++){
result += "<td>"+dataArray[i][j]+"</td>";
}
result += "</tr>";
}
To:
for(var i=0; i<dataArray.length; i++) {
result += dataArray[i].some(c => c.toUpperCase() == "ABSENT") ? '<tr style="background-color:red;">' : "<tr>";
for(var j=0; j<dataArray[i].length; j++){
result += "<td>"+dataArray[i][j]+"</td>";
}
result += "</tr>";
}
In this case, the row which has the value of ABSENT is set as the red background color. If you want to change the color, please modify above script.
Note:
If you want to set the background color for only the cells instead of the row, you can also use the following modification.
for(var i=0; i<dataArray.length; i++) {
result += "<tr>";
for(var j=0; j<dataArray[i].length; j++){
result += (dataArray[i][j].toUpperCase() == "ABSENT" ? '<td style="background-color:red;">' : "<td>") +dataArray[i][j]+"</td>";
}
result += "</tr>";
}
Added:
From your following replying,
#Tanaike I'm absolutely sorry, I made mistake by adding your code in wrong place, after placing the correct place, the login and table appears perfectly, but it doesn't highlight the row. this is the code your provided, 'for(var i=0; i<dataArray.length; i++) { result += dataArray[i].some(c => c.toUpperCase() == "Leave") ? '' : ""; for(var j=0; j<dataArray[i].length; j++){ result += ""+dataArray[i][j]+""; }'
It seems that you are testing the script using the value of Leave. In your question, the value is ABSENT. If you want to change the values to Leave, please modify above script as follows. Because toUpperCase() converts the characters to the upper case.
From:
for(var i=0; i<dataArray.length; i++) {
result += "<tr>";
for(var j=0; j<dataArray[i].length; j++){
result += "<td>"+dataArray[i][j]+"</td>";
}
result += "</tr>";
}
To:
for(var i=0; i<dataArray.length; i++) {
result += dataArray[i].some(c => c == "Leave") ? '<tr style="background-color:red;">' : "<tr>";
for(var j=0; j<dataArray[i].length; j++){
result += "<td>"+dataArray[i][j]+"</td>";
}
result += "</tr>";
}

How to convert multiple CSV file to Multiple HTML table using AJAX and Javascript

I have a code which will show an HTML table generated from a csv file on button click . but i want multiple csv file to convert to multiple HTML table on a single button click . Is it possible ?
So here is my script .
$(document).ready(function(){
$('#Load-Data').click(function(){
$.ajax({
url:"OutputNew.csv",
dataType:"text",
success:function(data){
var employee_data = data.split(/\r?\n|\r/);
var table_data = '<div class="dropdown"><button class="dropbtn">Download</button><div class="dropdown-content">Download PDFDownload HTMLDownload Excel</div></div><input type="text" id="myInput" onkeyup="myFunction()" placeholder="Search for names.."><div id="VMTable"><div id="content"><table id="myTable" class="table table-striped""><thead>';
for(var count = 0; count<employee_data.length; count++) {
var cell_data = employee_data[count].split(',');
table_data += '<tr>';
for(var cell_count=0; cell_count<cell_data.length; cell_count++){
if(count === 0){
table_data += '<th id="headers" style="position=sticky">'+cell_data[cell_count]+'</th>';
}else{
if(cell_data[cell_count] .includes("Not Matching")){
var ret = cell_data[cell_count].replace('Not Matching','');
if (ret == ""){
table_data += '<td>'+ret+'</td>'
}else{
table_data += '<td data-color="green"><span>'+ret+'</span></td>';
}
}else if(cell_data[cell_count] .includes("Matching")){
var ret = cell_data[cell_count].replace('Matching','');
if (ret == ""){
table_data += '<td>'+ret+'</td>';
}else if(ret == " "){
table_data += '<td>'+ret+'</td>';
}else{
table_data += '<td data-color="green"><span class="badge-complete" style="color:Green">'+ret+'</span></td>';
}
}else{
table_data += '<td>'+cell_data[cell_count]+'</td>';
}
}
}
table_data += '</tr>';
}
table_data += '</table></div><iframe id="txtArea1" style="display:none"></iframe>';
$('#employee_table').html(table_data);
}
});
});
});
and here is HTML button
<button type="button" name="Load-Data" id="Load-Data" class="btn btn-info">Generate Report</button>
Check out this snippet:
<!DOCTYPE html>
<html>
<head>
<title>CSV Files to HTML Tables</title>
<!-- JQuery -->
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
//add your files to csv_files array
var csv_files=['username.csv', 'username-password-recovery-code.csv']
$(document).ready(function(){
$('#btn_load').click(function(){
for(var i=0; i<csv_files.length; i++)
$.ajax({
url: csv_files[i],
dataType:'text',
success:function(data){
var rows = data.split(/\r?\n|\r/);
var table = '<table border="1">';
//row - iteration
//print table header
var headings = rows[0].split(";")
table += '<thead><tr>';
for(var j=0; j<headings.length; j++)
table += '<th>' + headings[j] + '</th>';
table += '</tr></thead>';
//print table body
table += '<tbody>';
for(var j=1; j<rows.length; j++){
var data_cell = rows[j].split(";")
table += '<tr>';
for(var k=0; k<headings.length; k++)
table += '<td>' + data_cell[k] + '</td>';
table += '</tr>';
}
table += '</tbody>';
//closing table, add line break, appending result to div
table += '</table><br>';
$('#div_results').append(table);
}
});
});
});
</script>
</head>
<body>
<div id="div_results" style="border: 5px outset grey; padding: 10px;">
<h2>--- Results ---</h2>
</div>
<button id="btn_load">Get External Content</button>
</body>
</html>
Because you haven't answered my questions I am presenting you a generalized solution. You can use this code to genereate HTML Tables for any no of CSVs having any no. of columns and rows. I have added <thead> and <tbody> tags for your ease. If you not wana use than you can remove them and do any further style specific alterations.

Creating div tag dynamically based on rows count

I have a database table which has rows. Based on the table rows, I want to create div tags dynamically. My requirement is like I have to create divs based on the database rows count.
If 5 rows are there in the db, then 1 div will be created.
If 20 rows are there in the db, then 2 divs will be created.
If 25 rows are there in the db, then 3 divs will be created.
If 56 rows are there in the db, then 6 divs will be created.
The 1st div should be beside the 2nd div.
Below is the javascript function I'm using:
function LoadData(data)
{
var rows_count = 22; -- will be fetched from DB side
var rowNum = Math.ceil(parseFloat(rows_count));
var resultHtml = '';
resultHtml += "<table style = \'width:100%;\' border=\'0\' colspan=\'2\' id=\'tbl_user\'>";
for (var i = 0; i <=rowNum-1 ; i++) {
resultHtml += '<tr>';
resultHtml += '<td border = 1><input type="name" placeholder="text goes here..."></td>';
resultHtml += '</tr>';
}
}
resultHtml += '</table>';
}
I have written out the logic, but 22 rows are creating only one div tag.
I want to show 10 records in 1 div and another 10 records in the 2nd div and so on.
Your Solution
$('#rows').change(function(e) {
var rows_count = parseInt($(this).val());
var div_count = Math.ceil(rows_count/10);
resultHtml = '<table width="100%" border="1px"><tr>';
j=0;l=0;
for (var i = 1; i<=div_count ; i++){k=0;
if(l==4){ resultHtml += '</tr><tr>';l=0;}
resultHtml += '<td align="center">';
while((j<rows_count)&&(k<10)){ resultHtml += '<input type="name" placeholder="text goes here..."><br>';j++;k++;}
resultHtml += '</td>';
l++;
}
resultHtml += '</tr></table>';
$('#inputs').html(resultHtml);
});
<link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css">
<style>.active {
background: red;
color:#FFF;
}</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="inputs"></div>
<input type="text" id="rows" placeholder="No. of Rows" />

i want to create new table dynamically and removed it by same button using jquery?

I want to show updated rows no every time. I have this code .want to remove and generate again as this same
var table = $('#table').children();
for (var j = i; j < result.length; j++) {
table.append("<tr><td>" + (j + 1) + "</td><td><b>" + result[j].VoterName + "</b></td><td><b>" + result[j].VoterContact + "</b></td><td><button>X</button></td></tr>");
i++;
}
function createOrDeleteTable(){
console.log("wadawdawd");
if($("#btn").attr("created") === "false") {
$("#btn").attr("created","true");
var tabledata = "<table>"
+ "<tr>"
+"<th> hey </th>"
+"<th> hello </th>"
+ "</tr>"
+ "</table>";
console.log(tabledata);
$("#appendHere").html(tabledata);
} else {
$("#btn").attr("created","false");
$("#appendHere").html("");
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button onclick="createOrDeleteTable();" created="false" id="btn"> create table </button>
<div id="appendHere"> </div>

Print a table inside a div with given row and column via Javascript

I have two textfield and one button. When user clicked the button, It calls a function and print a table inside a div with given number of rows and columns.
You can see my code below, but this is not working as expected.
HTML
Rows <input type="text" id="rows">
Columns <input type="text" id="columns">
<input type="button" value="Create Table" onClick="printTable();">
<div id="box"></div>
Javascript
function printTable()
{
var nRows=document.getElementById("rows");
var nColumns=document.getElementById("columns");
var spaceofDiv=document.getElementById("box");
spaceofDiv.innerHTML=("<table border=1>");
for(i=0; i<nRows.value; i++)
{
spaceofDiv.innerHTML=("<tr>");
for(j=0; j<nColumns.value; j++)
{
spaceofDiv.innerHTML=("<td width=50 height=50> ");
}
}
spaceofDiv.innerHTML=("</table>");
}
You need to remember to
A) Close your table row and table cell elements
B) Concatenate the value of the table markup, as you are currently overwriting your changes with each assignment
var markup = '';
markup = "<table border=1>";
for(i=0; i<nRows.value; i++)
{
markup += "<tr>";
for(j=0; j<nColumns.value; j++)
{
markup += "<td width=50 height=50> </td>";
}
markup += "</tr>";
}
markup = "</table>";
spaceofDiv.innerHTML = markup;
Try some thing this. Use a avariable add all string in to it and then set innerhtml. Als oyou are not closing the tr
function printTable()
{
var nRows=document.getElementById("rows");
var nColumns=document.getElementById("columns");
var spaceofDiv=document.getElementById("box");
var tableStr = "";
tableStr =("<table border=1>");
for(i=0; i<nRows.value; i++)
{
tableStr +="<tr>";
for(j=0; j<nColumns.value; j++)
{
tableStr +="<td width=50 height=50></td> ";
}
tableStr +="</tr>";
}
tableStr += "</table>"
spaceofDiv.innerHTML=tableStr;
}

Categories

Resources