I created a table with HTML, Js and express. This table for now get some data from a server request. I need to checkboxes and a SelectALL button/function for each row in this table. I'm not using Jquery or similar and in practice I use classList, querySelector and map to populate the table.
I would need this button to select aLL the rows (checkboxes) and then do something else with the data of the rows.
Anyone who knows how to help with that?
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
<link href="./src/app.css" rel="stylesheet" >
<title>Data Table w/ Refresh</title>
</head>
<body>
<div class="table-refresh" data-url="/data">
<!--
<table class="table-refresh__table">
<thead>
<tr>
<th>Tipo Doc</th>
<th>Data Doc</th>
<th>Importo</th>
<th>Prestatore</th>
<th>Committente</th>
</tr>
</thead>
<tbody>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
</tbody>
</table>
<div class="table-refresh__options">
<span class="table-refresh__label">Last Update:never</span>
<button type="button" class="table-refresh__button">
<i class="material-icons">refresh></i>
</button>
-->
</div>
<script src='./src/app.js'></script>
</body>
</html>
{
/**
* Populates a data table with some data.
*
* #param {HTMLDivElement} root
*/
async function updateTable(root){
root.querySelector(".table-refresh__button").classList.add("table-refresh__button--refreshing");
const table = root.querySelector(".table-refresh__table");
const response=await fetch(root.dataset.url)
const data = await response.json()
//clear table
table.querySelector("thead tr").innerHTML="";
table.querySelector("tbody").innerHTML="";
//populate headers
for (const header of data.headers) {
table.querySelector("thead tr").insertAdjacentHTML("beforeend", `<th>${ header }</th>`);
}
// Populate rows
for (const row of data.rows) {
table.querySelector("tbody").insertAdjacentHTML("beforeend", `
<tr>
${ row.map (col => `<td>${ col }</td>`).join("") }
</tr>
`);
}
//Update "last updated" text
root.querySelector(".table-refresh__label").textContent = `Last Update: ${ new Date(data.lastUpdated).toLocaleString()}`;
//Stop rotating
root.querySelector(".table-refresh__button").classList.remove("table-refresh__button--refreshing");
}
for (const root of document.querySelectorAll(".table-refresh[data-url]")) {
const table = document.createElement("table");
const options = document.createElement("div");
table.classList.add("table-refresh__table");
options.classList.add("table-refresh__options");
table.innerHTML = `
<thead>
<tr></tr>
</thead>
<tbody>
<tr>
<td>Loading</td>
</tr>
</tbody>
`;
options.innerHTML = `
<span class = "table-refresh__label">Last Update: never</span>
<button type="button" class="table-refresh__button">
<i class="material-icons">refresh</i>
</button>
`;
root.append(table, options);
options.querySelector(".table-refresh__button").addEventListener("click", () => {
updateTable(root);
});
updateTable(root);
}
}
Related
I have a jquery datatable of something like this
when i click the plus icon, it will show 2 buttons the capabilities and reimbursement, what I want is when i click the capabilities button, I want to get the parent row which are name, all and etc. Is that possible? I tried several method but it doesn't work.
What I tried is
function set_credentials(el) {
var tr = $(el).closest('tr').parents('tr');
var prevtr = tr.prev('tr')[0];
console.log(prevtr)
But i get the html dom.
I think I almost got it but i need some help. Thanks
Is this what you want? I console.log(name) for the result.
Example below
$("#example").on("click", set_credentials);
function set_credentials(event) {
if (event.target.tagName === "BUTTON") {
var tr = $(event.target).closest("tr");
var prevtr = tr.prev();
var name = prevtr.find("td.mws_name").text();
console.log(name);
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<title>Document</title>
</head>
<body>
<div>
<table id="example">
<thead>
<th>name</th>
<th>date</th>
<th>button</th>
</thead>
<tbody>
<tr>
<td class="mws_name">joe</td>
<td>2011-1-1</td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td><button>set</button></td>
</tr>
<tr>
<td class="mws_name">Sam</td>
<td>2011-5-1</td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td><button>set</button></td>
</tr>
</tbody>
</table>
</div>
</body>
</html>
Tying to sum up the dynamic input values in the last column of my table. If I hard code the number values then the calculation works just fine. If I input the values my self using a I get NaN
Ive used
My html table is added upon load and the rows are added as needed via a button.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<table id='table' border="1">
<tr>
<th>RO#</th>
<th>Work</th>
<th>Time</th>
</tr>
<tr>
<td>615235</td>
<td>lof, rotate</td>
<!-- <td>23</td> -->
<td><input type="number" /></td>
</tr>
<tr>
<td>6154879</td>
<td>engine, trans</td>
<!-- <td>23</td> -->
<td><input typ="number" /></td>
</tr>
<tr>
<td>6158978</td>
<td>rotate, serp belt, timing belt</td>
<!-- <td>23</td> -->
<td><input type="number" /></td>
</tr>
</table>
<br>
<button onclick='calculate()'>Calculate</button>
<script>
function calculate() {
let tbl = document.getElementById('table'),
sumVal = 0;
for (let i = 1; i < tbl.rows.length; i++) {
sumVal = sumVal + parseInt(tbl.rows[i].cells[2].input);
}
console.log(sumVal);
}
</script>
</body>
</html>
I get NaN when using the <td><input type="number or type="text"><td> code
The problem is that the input property does not exist in tbl.rows[i].cells[2]. Honestly, I don't know if it's possible to get the input values from Table cells Collection that you're trying to utilize.
I suggest this approach, using querySelectorAll in which we specify the inputs we'd like to get data from:
function calculate() {
let tbl = document.querySelectorAll("table input[type='number']"),
sumVal = 0;
for (let i = 0; i < tbl.length; i++) {
sumVal += Number(tbl[i].value);
}
console.log(sumVal);
}
i want in table seven header are there example:numbers,assending order,decending order,max values,min values,sum of all values,avg values...
an array values i had taken random values....and it should be entered in no of rows and only in 1 column...
html code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Array</title>
</head>
<body>
<table id="table" border="2" style="border:12px solid brown">
<tr>
<th>numbers</th>
<th>assending order</th>
<th>decenting order</th>
<th>max value</th>
<th>minimum value</th>
</tr>
<tr >
<td></td>
</tr>
<p id="all">sd</p>
</table>
<script>
var array=[["1"],["5"],["10"],["6"],["3"],["17"],["19"],["24"],["7"],["8"],["11"],
["13"],["15"],["15"],["12"],["14"],["16"],["18"],["21"],["20"]],
table=document.getElementById("table")
for(i=1;i<array.length;i++){
for(j=0;j<table.rows[i].cells[0].length;j++){
table.rows[i].cells[0].innerHTML=array[i][j];
console.log(table.rows[i].cells[0].innerHTML=array[i][j])
}
}
</script>
</body>
</html>
You need to follow these steps:
Get the reference of the table through it's id value as document.getElementById("table")
set the value of array which you want to fill in the table. Also set the number of columns value in a variable, say columns so that you can loop over each column and fill the values for each row in each column.
Create a new row table.insertRow(i+1); below each created row
Create columns for each row row.insertCell(j);
Insert the value in each column from the array cells[j].innerHTML=array[i][j];
var array=[["1"],["5"],["10"],["6"],["3"],["17"],["19"],["24"],["7"],["8"],["11"],
["13"],["15"],["15"],["12"],["14"],["16"],["18"],["21"],["20"]];
var table = document.getElementById("table");
var columns = 5;
for(i=0;i<array.length;i++){
var row = table.insertRow(i+1);
var cells = [];
for(j=0;j<columns;j++){
cells[j] = row.insertCell(j);
if(array[i][j]){
cells[j].innerHTML=array[i][j];
}
}
}
<table id="table" border="2" style="border:12px solid brown">
<tr>
<th>numbers</th>
<th>assending order</th>
<th>decenting order</th>
<th>max value</th>
<th>minimum value</th>
</tr>
<p id="all">Table</p>
</table>
I want to change Background color of row based on cell data, like if it matches first four characters from table cell "td", then row should change its color to red.
here is my example, it is working but it takes whole cell data.but i want row color should change once it matches first four characters from cell.
<style>
.bgRed{
background-color:red;
}
</style>
<body ng-app="myApp">
<div ng-controller="myController">
<div class="container" style="margin-top:40px;">
<div class="row">
{{error}}
<div class="col-md-6">
<table class="table table-bordered table-condensed">
<thead>
<tr>
<th>Name</th>
<th>Class Name</th>
<th>Roll No</th>
<th>Email</th>
</tr>
</thead>
<tbody ng-repeat="std in students">
**<tr ng-class="{'bgRed': std.Name === 'Prash'}>**
<td>{{std.Name}}</td>
<td>{{std.ClassName}}</td>
<td>{{std.RollNo}}</td>
<td>{{std.Email}}</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
</div>
</body>
and my table is
Table row should change to red if table cell data "Prash or Prashant" matches.instead of taking "Prashant Olekar"
how to achive this please help. Thank you
Using substring you can trim the characters of the string,
here I'm creating one more variable(filed) "trimmed_name" which is a substring of your "name" which gives you first 4 characters of your string "name".
<tr ng-repeat="std in students" ng-init="trimName(std)">
<td ng-class="{'bgRed': std.trimmed_name === 'Prash', 'bgBlue': std.trimmed_name === 'Pavi', 'bgBlack' : std.trimmed_name === 'Pava'}">{{std.Name}}</td>
<td>{{std.ClassName}}</td>
<td>{{std.RollNo}}</td>
<td>{{std.Email}}</td>
</tr>
In Css add respective colours for respective classes
in your controller
$scope.trimName = function (std) {
std.trimmed_name = std.Name.substring(0, 4);
return std;
};
Just in case if 'Prash' dose not work use {'bgRed': std.trimmed_name === "Prash"}
Hope it helps you.
you can use a custom filter to set class according to condition of your row data,
html
<tbody ng-repeat="std in students | filter:filterColor">
<tr class="{{std.class}}">
<td>{{std.Name}}</td>
<td>{{std.ClassName}}</td>
<td>{{std.RollNo}}</td>
<td>{{std.Email}}</td>
</tr>
</tbody>
js
$scope.filterColor = function (item) {
if (your condition) {
item.class = 'your class';
}
else
item.class = 'some other class';
return true;
};
I have got solution to my question with the help of Rajat, here is my code. but it only matches characters from 0th Position.
<head>
<title></title>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="Content/bootstrap.min.css" rel="stylesheet" />
<script src="Scripts/angular.min.js"></script>
<script src="Scripts/App/app.js"></script>
<style>
.bgRed {
background-color: #cfeaff;
}
</style>
</head>
<body ng-app="myApp">
<div ng-controller="myController">
<div class="container" style="margin-top:40px;">
<div class="row">
{{error}}
<div class="col-md-6">
<table class="table table-bordered table-condensed">
<thead>
<tr>
<th>Name</th>
<th>Class Name</th>
<th>Roll No</th>
<th>Email</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="std in students" ng-init="trimName(std)" ng-class="{bgRed: std.trimmed_name === 'Pras'}">
<td>{{std.Name}}</td>
<td>{{std.ClassName}}</td>
<td>{{std.RollNo}}</td>
<td>{{std.Email}}</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
</div>
</body>
</html>
and In Controller
/// <reference path="../angular.min.js" />
var myApp = angular.module('myApp', [])
.controller("myController", function ($scope, $http, $log) {
var successCallback = function (response) {
$scope.students = response.data;
$log.info(response);
}
var errorCallback = function (response) {
$scope.error = response.data;
$log.info(response);
}
$scope.StudentsData = $http({
method: 'GET',
url: 'PKWebService.asmx/getPkData'
})
.then(successCallback, errorCallback);
$scope.trimName = function (std) {
std.trimmed_name = std.Name.substring(0, 4);
return std;
};
});
and output is
Thank you
I am fairly new to knockoutjs. I am creating a simple table and trying to sum up all the values in the "total" column. Plus, I am also implementing "Add column" and "Remove Column" functionalities using knockoutjs.
The problem is that both the Add and Remove funcitonalities and not working. Plus,the "TotalSurcharge" value is not displaying on the UI.
Here's my js:
// Class to represent a row in the table
function addMaterial() {
this.name = ko.observable("");
this.quantity = ko.observable("");
this.rate = ko.observable(0);
this.formattedTotal = ko.computed(function() {
return this.rate() * this.quantity();
}, this);
}
function documentViewModel(){
var self = this;
//create a mateirals array
self.materials = ko.observableArray([
new addMaterial()
]);
// Computed data
self.totalSurcharge = ko.computed(function() {
var total = 0;
for (var i = 0; i < self.materials().length; i++)
total += self.materials()[i].formattedTotal();
return total;
});
// Operations
self.addMaterial = function() {
self.materials.push(new addMaterial());
}
self.removeMaterial = function(material) { self.materials.remove(material) }
}
ko.applyBindings(new documentViewModel());
Here's my HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<title>Bootstrap Example</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js"></script>
<script type='text/javascript' src='knockout-2.2.0.js'></script>
</head>
<body>
<div class="container">
<table class="table table-bordered">
<thead>
<tr>
<th>Item</th>
<th>Quantity </th>
<th>Rate</th>
<th>Total</th>
</tr>
</thead>
<tbody "foreach: materials">
<tr class="info">
<td><input data-bind="value: name" /></td>
<td><input data-bind="value: quantity" /></td>
<td><input data-bind="value: rate" /></td>
<td data-bind="text: formattedTotal"></td>
<td>Remove</td>
</tr>
</tbody>
</table>
<button data-bind="click: addMaterial, enable: materials().length < 5">Add Row</button>
<h3 data-bind="visible: totalSurcharge() > 0">
Total surcharge: $<span data-bind="text: totalSurcharge().toFixed(2)"></span>
</h3>
</div>
</body>
<script type='text/javascript' src='application.js'></script>
</html>
I checked the console error on the browser but am not getting any error. Any idea what am I doing wrong?
I think you intended to bind the materials to the table body, this is not right:
<tbody "foreach: materials">
It should be:
<tbody data-bind="foreach: materials">
Once that is fixed, everything else appears to work.
fiddle