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

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>";
}

Related

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.

Adding a new column to html table using 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>';
}

javascript to create table php mysql to save data

I need a table where the user enters how many rows and columns needed, they enter the numbers and the next page creates the table.
They will enter the info which will be saved into a database. The only way I can think to do this is with dynamic tables, is there a better way? Here is some super basic code, I haven't worked out the full table, wanted to get feedback before I continue in case there is a better way and I need to change course.
Simple form:
How many rows <input type="number" id="rowNumber"/><br>
How many columns <input type="number" id="colNumber"/><br>
<button onclick="myFunction()">Checkout</button>
function myFunction() {
var rowNumber = document.getElementById('rowNumber').value;
var colNumber = document.getElementById('colNumber').value;
window.location.href = "website/test.php?rowNumber="+rowNumber+"&colNumber="+colNumber;
}
test.php
<?php
$rowNumber=$_GET['rowNumber'];
$colNumber=$_GET['colNumber'];
?>
<script>
var numRows = "<? echo $rowNumber ?>";
var numCols = "<? echo $colNumber ?>";
var tableString = "<table>",
body = document.getElementsByTagName('body')[0],
div = document.createElement('div');
for (row = 1; row < numRows; row += 1) {
tableString += "<tr onclick=\"fnselect(this)\"<? if($rowID == "A") { echo "class ='selected'";} ?>>";
for (col = 1; col < numCols; col += 1) {
tableString += "<td>" + "R" + row + "C" + col + "" + "<input type='text' />" + "</td>";
}
tableString += "</tr>";
}
tableString += "</table>";
div.innerHTML = tableString;
body.appendChild(div);
</script>
Looking into jQuery DataTables. A lot of nice functionality in there.
You can either bind to a JSON data source, or create your own rows manually like this URL:
https://datatables.net/examples/api/add_row.html
So, to use this, you have to reference jquery AND the data tables script. You'll have to either reference them from their given URLs, or download the scripts (I recommend the latter otherwise you create references to outside servers).

Adding data into a table and saving it into a database

I've created a form when the user inputs the number of rows of the table which corresponds to number of subjects.I want the user to insert data into this table's columns or to fill it.How can i make this because my table just stands there chillin' and i can't insert data into it.
This is my code. Please someone shows me how to insert data into the columns of this table instead of phrases"one" and "two" i've used for demonstration.This code doesn't have errors so works very well.
<html>
<head>
<title>
</title>
</head>
<body>
Insert nr of subjects
<input type="text" id="row"></input>
<button onclick="myFunction()" >Sub </button>
<div id="container"></div><!--hapesira qe i kemi lene tabeles ne faqe-->
<script>
function myFunction(){
//Get the value the user gave
var nr = document.getElementById("row").value;
//e kthej ne int nga string qe esht
var c=parseInt(nr);
var div=document.getElementById("container");
div.innerHTML = " ";
div.innerHTML += "<table border='1' id='table'>";
document.getElementById('table').innerHTML += "<tr><td>SUBJECT</td><td>POINTS</td></tr>";
for (i = 0; i < c; i++) {
//Write the rows and cells
document.getElementById('table').innerHTML += "<tr><td> one </td><td> two </td></tr>";
}
}
</script>
</body>
</html>
I changed your code to insert inputs instead of "one" and "two", with classes subject and points. To store this information you will have to grab each row of your table and pull out the value of those inputs, and store it in the database.
function myFunction(){
//Get the value the user gave
var nr = document.getElementById("row").value;
//e kthej ne int nga string qe esht
var c=parseInt(nr);
var div=document.getElementById("container");
div.innerHTML = " ";
div.innerHTML += "<table border='1' id='table'>";
document.getElementById('table').innerHTML += "<tr><td>SUBJECT</td><td>POINTS</td></tr>";
for (i = 0; i < c; i++) {
//Write the rows and cells
document.getElementById('table').innerHTML += '<tr><td><input type="text" class="subject" /></td><td><input type="text" class="points"/></td></tr>';
}
}
You use HTML input elements to allow the user to enter data into a form.
http://www.w3schools.com/tags/tag_input.asp
Please add input elements when you are adding rows. Try this:
<html>
<head>
<title>
</title>
</head>
<body>
Insert nr of subjects
<input type="text" id="row"></input>
<button onclick="myFunction()" >Sub </button>
<div id="container"></div><!--hapesira qe i kemi lene tabeles ne faqe-->
<script>
function myFunction(){
//Get the value the user gave
var nr = document.getElementById("row").value;
//e kthej ne int nga string qe esht
var c=parseInt(nr);
var div=document.getElementById("container");
div.innerHTML = " ";
div.innerHTML += "<table border='1' id='table'>";
document.getElementById('table').innerHTML += "<tr><td>SUBJECT</td><td>POINTS</td></tr>";
for (i = 0; i < c; i++) {
//Write the rows and cells
document.getElementById('table').innerHTML += "<tr><td><input type='text' id= 'sub'> </td><td><input type='text' id='points'></td></tr>";
}
}
</script>
</body>
</html>
Cheers !

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