change color of table cell using jsp - javascript

i have a jsp file which prints a mysql table with the help of jdbc.The columns of table are id, name , division and age.I want to change the color of table cell with age data to change red and green depending upon some particular values.
<body>
<%!Connection con; %>
<%!Statement s; %>
<% ResultSet rs=null;
String name=request.getParameter("t1");
try{
Class.forName("com.mysql.jdbc.Driver");
con=DriverManager.getConnection("jdbc:mysql://localhost:3307/****","root","****");
s=con.createStatement();
System.out.println(name);
rs=s.executeQuery("select * from employee");
}catch(Exception e){ e.printStackTrace(); }
%>
<div id="dt_table">
<table border=1>
<tr>
<th>Empolyee ID</th>
<th>Empolyee Name</th>
<th>Employee Division</th>
<th>age</th>
</tr>
<tr>
<% try
{
while(rs.next())
{ %>
<tr>
<td><%=rs.getInt(1)%></td>
<td><%=rs.getString(2)%></td>
<td><%=rs.getString(3)%></td>
<td><%=rs.getInt(4)%></td>
</tr>
<% }
}catch(Exception e){ e.printStackTrace(); }%>
</table></div>
</body>
This question has been already asked but it has not been answered.Here's the link.
https://stackoverflow.com/questions/23131874/change-color-of-table-based-on-values-of-mysql-database-using-jsp
I even found something like this in php, but i donot know php,
Change color of table based on values from SQL Query database using PHP
So any help in jsp or javascript may be helpful.Thanks.

You could do this based on the header of the table
function colorIt() {
var val = 0; //value to be compared with
var val2 = 10; //value to be compared with
var ColIndexToCheck = 0;
var header = document.getElementById("dt_table").getElementsByTagName("th");
for (var j = 0; j < header.length; j++) {
if (header[j].innerHTML == "Age") {
ColIndexToCheck = j;
}
}
var trs = document.getElementById("dt_table").getElementsByTagName("tr");
for (var i = 0; i < trs.length; i++) {
if (trs[i].cells[ColIndexToCheck].innerHTML > val) {
trs[i].cells[ColIndexToCheck].style.backgroundColor = "red";
}
if (trs[i].cells[ColIndexToCheck].innerHTML > val2) {
trs[i].cells[ColIndexToCheck].style.backgroundColor = "green";
}
}
}

Try this, suppose the fourth column is the age in table:
while(rs.next()) {
{ %>
<tr>
<td><%=rs.getInt(1)%></td>
<td><%=rs.getInt(2)%></td>
<td><%=rs.getInt(3)%></td>
<td <%=(rs.getInt(1) > 10 : "style='background-color:red;'" : "")%> ><%=rs.getInt(1)%></td>
</tr>
<% } %>
Or you simply use If-else if you want.
Hope, it helps!!

Related

How do I insert certain values of an array as a CSS style property for a <td> in a dynamic table?

I have a script that collects data from an array and uses these to generate a dynamic table. Some of these values in the array are Font Awesome styles.
My existing script inserts all the values in the array into each table cell.
The intention is for the Font Awesome style values to be inserted as a cell style, during the rendering of the table.
In the code below, notice that the array properties for paymentStatus stores a CSS Font Awesome style value.
var array = [{
amount: 12,
payersNumber: 1245,
paymentStatus: class="fas fa-exclamation-triangle"
}];
table = document.getElementById("table");
var currentTransaction;
var keys = ["payersNumber", "amount", "paymentStatus"];
for (var i = 0; i < array.length; i++) {
console.log("Number of transactions: " + array.length);
var newRow = table.insertRow(table.length);
currentTransaction = array[i];
for (var b = 0; b < keys.length; b++) {
var cell = newRow.insertCell(b);
cell.innerText = currentTransaction[keys[b]];
}
}
How do I get the paymentStatus values to get inserted into the table as the style for each <th>Status</th> column?
Find below the HTML table that my existing code geneates:
<table id="table" border="1">
<tr>
<th>Amount</th>
<th>Number</th>
<th>Status</th>
</tr>
</table>
<tr>
<td> 12 </td>
<td> 1245 </td>
<td> class="fas fa-exclamation-triangle" </td>
</tr>
For the Font Awesome style to successfully be put in effect, it needs to be inserted into the <td> </td> as a class style.
The desired effect would, therefore, look like this:
<table id="table" border="1">
<tr>
<th>Amount</th>
<th>Number</th>
<th>Status</th>
</tr>
<tr>
<td>12</td>
<td>1245</td>
<td class="fas fa-exclamation-triangle"></td>
</tr>
</table>
Inside the nested for-loop you can make a distinction based on the current value of keys[b]. If it's paymentStatus add an <i> tag with the css for the font awesome exclamation mark and use the .innerHTML property of the cell. If it's something else just assign the appropriate text to the .innerText proeprty.
var array = [{
amount: 12,
payersNumber: 1245,
paymentStatus: "okay"
}, {
amount: 24,
payersNumber: 3345,
paymentStatus: "okay"
}, {
amount: 45,
payersNumber: 4534,
paymentStatus: "not okay"
}];
table = document.getElementById("table");
var currentTransaction;
var keys = ["payersNumber", "amount", "paymentStatus"];
for (var i = 0; i < array.length; i++) {
var newRow = table.insertRow(table.length);
currentTransaction = array[i];
for (var b = 0; b < keys.length; b++) {
var cell = newRow.insertCell(b);
if (keys[b] == "paymentStatus") {
cell.innerHTML = "<i class='fas fa-exclamation-triangle'></i>" + currentTransaction[keys[b]];
} else {
cell.innerText = currentTransaction[keys[b]];
}
}
}
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.10.0/css/all.css">
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.10.0/css/v4-shims.css">
<table id="table" border="1">
<tr>
<th>Number</th>
<th>Amount</th>
<th>Status</th>
</tr>
</table>
You can use classList.add method to add css class to HTML element as follows:
for (var b = 0; b < keys.length; b++) {
var cell = newRow.insertCell(b);
if (keys[b] == 'paymentStatus') {
let className = '';
// it is assumed that paymentStatus value format is consistent
const classNameArr = currentTransaction[keys[b]].split('=');
if (classNameArr.length === 2) {
className = classNameArr[1];
cell.classList.add(className);
}
} else {
cell.innerText = currentTransaction[keys[b]];
}
}

Passing variable from ejs to js script

I am trying to pass a variable from ejs to JavaScript function but keep getting undefined in output. Here is the code. It is supposed to render a table with file names and clicking on each file name should later redirect to a page which would render the file in the browser but I can't proceed without passing the parameter to URL.
<% if (files.length > 0) {%>
<table class="table table-hovered">
<thead class="thead-light">
<tr>
<th scope="col">No</th>
<th scope="col">File</th>
<% files.forEach((file, index) => { %>
<tr>
<th scope="row">
<%= index + 1 %>
</th>
<td>
<a onclick="func(file.fileName);">
<%= file.fileName %>
</a>
</td>
</tr>
<% }) %>
</tbody>
</table>
<% } %>
</div>
</div>
<script>
function func(fileName) {
window.location.href = "/thesis_view/" + fileName;
}
</script>
getStudentUploadThesisPage: (req, res) => {
const getFilesQuery = "SELECT fileName FROM supervision INNER JOIN thesis ON supervision.thesisId = thesis.id INNER JOIN thesis_details ON thesis_details.thesisId = thesis.Id INNER JOIN people ON supervision.teacherId = people.id INNER JOIN thesis_file ON thesis_details.id = thesis_file.thesis_detail_id WHERE supervision.studId = " + req.session.userId;
db.query(getFilesQuery, (err, result) => {
if (err) {
return res.status(500).send(err);
} else if (result.length >= 0) {
res.render('student_upload_thesis', {
files: result
});
}
});
}
I have come up with something like this. It does it job
<script>
var table = document.getElementById('table'),
rIndex;
for (var i = 0; i < table.rows.length; i++) {
table.rows[i].onclick = function () {
rIndex = this.rowIndex;
window.location.href = "/thesis_view/" + this.cells[1].innerHTML;
}
}
</script>

How to merge rows based on <td> class? (Javascript)

I'm currently trying to make it so that when the JS code does its thing, the rows with common values and common classes will be merged. The code worked, but all of the common rows were merged without taking into account their classes.
Table code:
<tbody id="property_dtl_table_body">
<% dtls.each do |f| %>
<tr class="<%= payment_paid(f.paid)%>" id="paidrow">
<td>
<% if !f.paid %>
<%= check_box_tag "pin_number[]", f.id, checked= !f.paid? %>
<%end%>
</td>
<td id="pin"><%= f.year %></td>
<td><%= f.quarter %></td>
<td align="right" id="price"><%= number_to_currency(f.amount, unit: "",
precision: 2)%></td>
</tr>
<%end%>
</tbody>
JS Code:
if(!$(this).hasClass('paid')){
var table = $("#property_dtl_table_body");
var rows = table.find($("tr"));
var colsLength = 2;
var removeLater = new Array();
for(var i=1; i<colsLength; i++){
var startIndex = 0;
var lastIndex = 0;
var startText = $($(rows[0]).find("td")[i]).text();
for(var j=1; j<rows.length; j++){
var cRow =$(rows[j]);
if(!$(this).hasClass('paid')){
var cCol = $(cRow.find("td")[i]);
}
var currentText = cCol.text();
if(currentText==startText){
cCol.css("background","gray");
console.log(cCol);
removeLater.push(cCol);
lastIndex=j;
}else{
var spanLength = lastIndex-startIndex;
if(spanLength>=1){
console.log(lastIndex+" - "+startIndex)
//console.log($($(rows[startIndex]).find("td")[i]))
$($(rows[startIndex]).find("td")
[i]).attr("rowspan",spanLength+1);
}
lastIndex = j;
startIndex = j;
startText = currentText;
}
}
var spanLength = lastIndex-startIndex;
if(spanLength>=1){
console.log(lastIndex+" - "+startIndex)
//console.log($($(rows[startIndex]).find("td")[i]))
$($(rows[startIndex]).find("td")
[i]).attr("rowspan",spanLength+1);
}
console.log("---");
}
for(var i in removeLater){
$(removeLater[i]).remove();
}
}
The class in question(#paid) is represented by the green background color as seen here:
Before JS:
After JS:
Expected result:
You can go for the following logic:
Start on the first year td
Loop through the next year td's until you find a different one and count them
When you find one, set the first td's rowspan to the number of elements in between
Remove all those td's that you looped through
Repeat the process until the end
The same classe restriction only applies to the selector that you use to fetch all the tds.
Example:
function mergeByClass(className){
let currTd, count = 0;
$(`tr > .${className}`).each(function(){
if (!currTd) //if its the first one set it as current
currTd = $(this);
else { //if its not
if ($(this).text() == currTd.text()){ //check if its a repeating one
count++; //count if it is
$(this).remove(); //and remove it to properly merge
}
else { //if its a different one
if(count >= 1) //merge if it has 1 or more in between
currTd.attr("rowspan", count + 1);
currTd = $(this); //reset the current one
count = 0;
}
}
});
if (count >= 1) //last element case
currTd.attr("rowspan", count + 1);
}
$("#merge").on("click", () => mergeByClass("paid"));
td {
border: 1px solid black;
padding : 15px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="merge">Click to merge rows with the same class</button>
<table>
<tr>
<td class="paid">2015</td><td>3</td><td>22.97</td>
</tr>
<tr>
<td class="paid">2015</td><td>3</td><td>22.97</td>
</tr>
<tr>
<td>2016</td><td>3</td><td>22.97</td>
</tr>
<tr>
<td>2016</td><td>3</td><td>22.97</td>
</tr>
<tr>
<td>2017</td><td>3</td><td>22.97</td>
</tr>
<tr>
<td>2017</td><td>3</td><td>22.97</td>
</tr>
<tr>
<td>2017</td><td>3</td><td>22.97</td>
</tr>
<tr>
<td class="paid">2018</td><td>3</td><td>22.97</td>
</tr>
<tr>
<td class="paid">2018</td><td>3</td><td>22.97</td>
</tr>
</table>

How do I use themes with jsPDF-AutoTable?

I don't get how I use the themes for jsPDF-AutoTable. . .
This is my Code to generate the PDF:
function tbl1ToPDF(){
var table = tableToJson($('#tbl1').get(0));
var doc = new jsPDF('l','pt','letter',true);
$.each(table, function(i, row){
$.each(row, function(j,cell){
if(i == 0)
{
doc.cell(10,10,150,50,cell,i, 'center');
}
else
{
doc.cell(10,10,150,120,cell,i,'center');
}
});
});
doc.save('Sofort.pdf');
}
And this is my tableToJson function:
function tableToJson(table) {
var data = [];
var headers = [];
for (var i = 0; i < table.rows[0].cells.length; i++) {
headers[i] = table.rows[0].cells[i].innerHTML.toLowerCase().replace(/ /gi, '');
}
data.push(headers);
// go through cells
for (var i = 1; i < table.rows.length; i++) {
var tableRow = table.rows[i];
var rowData = {};
for (var j = 0; j < tableRow.cells.length; j++) {
rowData[headers[j]] = tableRow.cells[j].innerHTML;
}
data.push(rowData);
}
return data;
}
My Table is dynamic. I generate it after pressing a Button but the struct of the Table looks like this:
<h3>Header</h3>
<table id="tbl1">
<thead>
<tr>
<th>Nr</th>
<th>Name</th>
<th>Unit</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>test</td>
<td>test</td>
</tr>
<tr>
<td>2</td>
<td>test</td>
<td>test</td>
</tr>
</tbody>
</table>
<input type="button" onclick="tbl1ToPDF" value="download">
Can you please help me applying a theme to my PDF? I never did this before and I really need help!
Thanks you!
In order to use jsPDF-Autotable plugin you need to call it inside the code like so:
var doc = new jsPDF();
doc.autoTable();
Once you called autoTable, you can apply some option to it like "theme" this way:
doc.autoTable({theme: 'grid'});
For example, I have an HTML table (3 columns) with id = "table-report-p2p"
I get the data from it with autoTableHtmlToJson() and then I applied some options.
This is the code that works for me:
var elem = document.getElementById("table-report-p2p");
var res = doc.autoTableHtmlToJson(elem);
doc.autoTable(res.columns, res.data, {
theme: 'grid',
startY: 150,
margin: {horizontal: 10},
pageBreak: 'auto',
rowPageBreak: 'avoid',
columnStyles: {0: {cellWidth: 35, minCellHeight: 53},1: {cellWidth: 70},2: {cellWidth: 84}}
});

How to check for duplicate row using javascript

how do I check for duplicate row in a table using javascript? The following is part of my code:
<table id="t1">
<tr>
<td>Text A</td>
<td>Text B</td>
<td>Cbx A</td>
</tr>
<% int count1 = -1;
for(int i=0; i<3; i++) { %>
<tr>
<td><input type="text" id="textA<%=i%>"></td>
<td><input type="text" id="textB<%=i%>"></td>
<td><select name="cbx_A<%=i%>">
<option value="A">Option1</option>
<option value="B">Option2</option>
</select>
</td
</tr>
<%count1 =i;
}%>
<tr>
<td><input type="button" onclick="check(<%=count1%>)" value="Check"></td>
</tr>
</table>
So based on this code, I will have 3 rows of text A,textB and cbxA. With that, how do I check whether user input the same values for 2 of the rows or all three rows?
I tried using servlet but theres too much work involve. So yeah is there a way to do this using java script instead?
Thanks in advance for any possible help.
Using this code it will check for duplication in one table column
then take all rows of table that are duplicated and put their ids in array
so you will get an array of rows id
but ur table has to have an id for each row
var columnNumber = 1;
var table = document.getElementById('t1');
var rowLength = table.rows.length;
var arrReocrds = new Array();
var arrCount = 0;
var listCount = 0;
var arr = new Array();
$('#t1 td:nth-child(' + colNumber + ')').each(function () {
var recordValue = $(this).html().trim();
var flagFirstTime = true;
//loop through table to check redundant of current record value
for (var i = 1; i < rowLength; i += 1) {
{
var row = table.rows[i];
var recordId = //put here row.id or anything that you can put it in the list
var cell = row.cells[colNumber - 1];
var value = cell.innerText.trim();
if (value == recordValue) {
if (!arr.contains(value)) {
if (flagFirstTime != true) {
arrReocrds[arrCount] = recordId;
arrCount++;
}
else
flagFirstTime = false;
}
else
break;
}
}
}
//create list for items in column
//to be sure that the item that has been taken and checked never be checked again by their other redundant records
arr[listCount] = recordValue;
listCount++;
});

Categories

Resources