I want to allow the user to reorder the columns in the table by dragging and dropping them. I am using jquery.dragtable.js to allow drag and drop. It`s working fine. Now I want to store the table order after drag and drop on the client-side and restore the state onload.
Here is my HTML Code:
<table id="tblReg" class="table table-bordered">
<thead>
<tr>
<th>#</th>
<th>First Name</th>
<th>Last Name</th>
<th>Username</th>
<th>Password</th>
<th>Email</th>
<th>Phone</th>
</tr>
</thead>
<tbody>
<tr>
<th>1</th>
<td>Mark</td>
<td>Otto</td>
<td>#mdo</td>
<td>545trt574</td>
<td>Na#email.com</td>
<td>7788994320</td>
</tr>
<tr>
<th>2</th>
<td>Jacob</td>
<td>Thornton</td>
<td>#fat</td>
<td>yffft5456</td>
<td>Na#email.com</td>
<td>7788994320</td>
</tr>
<tr>
<th>3</th>
<td>Larry</td>
<td>the Bird</td>
<td>#twitter</td>
<td>fgfhgf444</td>
<td>Na#email.com</td>
<td>7788994320</td>
</tr>
<tr>
<th>4</th>
<td>Rima</td>
<td>the Bird</td>
<td>#twitter</td>
<td>jjk8899</td>
<td>Na#email.com</td>
<td>7788994320</td>
</tr>
<tr>
<th>5</th>
<td>Sundar</td>
<td>the Bird</td>
<td>#twitter</td>
<td>76767687hjh</td>
<td>Na#email.com</td>
<td>7788994320</td>
</tr>
</tbody>
</table>
Get Table Order
<p class="porder"></p>
Jquery:
$(document).ready(function(){
$('#tblReg').each(function(){
$(this).dragtable({
placeholder: 'dragtable-col-placeholder',
items: 'thead th:not( .notdraggable ):not( :has( .dragtable-drag-handle ) ), .dragtable-drag-handle',
appendTarget: $(this).parent(),
scroll: true
});
});
$('a.order').click(function(){
console.log($('#tblReg').dragtable('order'));
var curOrder = $('#tblReg').dragtable('order');
$('.porder').text(curOrder);
return false;
});
});
Plugin Refer: https://github.com/akottr/dragtable
The allow to provide get the table order as follows:
["#", "First Name", "Last Name", "Username", "Password", "Email", "Phone"]
Now I want to store this in client side (LocalStorage / Cookies) and reorder OnLoad as per save data.
How to do this? I'm new in jquery.
Try this code, Its working fine.
Columns ordering set into sessionStorage after drag-n-drop and then refresh your page. You will see columns order change.
Ordering records in array format, You can see in console:
<!DOCTYPE html>
<html>
<head>
<title>Reorder</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<link rel="stylesheet" type="text/css" href="//rawgithub.com/akottr/dragtable/master/dragtable.css" />
</head>
<body>
<div class="container-fluid">
<div class="row">
<div class="col-sm-12">
<table id="tblReg" class="table table-bordered">
<thead>
<tr class="active">
<th id="number">#</th>
<th id="fname">First Name</th>
<th id="lname">Last Name</th>
<th id="uname">Username</th>
<th id="pass">Password</th>
<th id="email">Email</th>
<th id="phone">Phone</th>
</tr>
</thead>
<tbody>
<tr>
<th>1</th>
<td>Mark</td>
<td>Otto</td>
<td>#mdo</td>
<td>545trt574</td>
<td>Na#email.com</td>
<td>7788994320</td>
</tr>
<tr>
<th>2</th>
<td>Jacob</td>
<td>Thornton</td>
<td>#fat</td>
<td>yffft5456</td>
<td>Na#email.com</td>
<td>7788994320</td>
</tr>
<tr>
<th>3</th>
<td>Larry</td>
<td>the Bird</td>
<td>#twitter</td>
<td>fgfhgf444</td>
<td>Na#email.com</td>
<td>7788994320</td>
</tr>
<tr>
<th>4</th>
<td>Rima</td>
<td>the Bird</td>
<td>#twitter</td>
<td>jjk8899</td>
<td>Na#email.com</td>
<td>7788994320</td>
</tr>
<tr>
<th>5</th>
<td>Sundar</td>
<td>the Bird</td>
<td>#twitter</td>
<td>76767687hjh</td>
<td>Na#email.com</td>
<td>7788994320</td>
</tr>
</tbody>
</table>
</div>
</div>
<div class="row">
<div class="col-sm-12">
Get Table Order
<p class="porder"></p>
</div>
</div>
</div>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.10.2/jquery-ui.min.js"></script>
<script src="//rawgithub.com/akottr/dragtable/master/jquery.dragtable.js"></script>
<script type="text/javascript">
$(document).ready(function(){
// this code for sessionStorage
$('#tblReg').dragtable({
persistState: function(table) {
if (!window.sessionStorage) return;
var ss = window.sessionStorage;
table.el.find('th').each(function(i) {
if(this.id != '') {table.sortOrder[this.id]=i;}
});
ss.setItem('tableorder', JSON.stringify(table.sortOrder));
},
restoreState: eval('(' + window.sessionStorage.getItem('tableorder') + ')')
});
// this code for each th drag and drop
$('#tblReg').each(function(){
$(this).dragtable({
placeholder: 'dragtable-col-placeholder',
items: 'thead th:not(.notdraggable):not(:has(.dragtable-drag-handle)), .dragtable-drag-handle',
appendTarget: $(this).parent(),
scroll: true
});
});
// Click and then you see ordering of (th) in console.
$('a.order').click(function(e){
e.preventDefault();
var order_array = [];
$('#tblReg').dragtable().find('thead th').each(function(i,v){
order_array.push($(v).text());
});
console.log(order_array);
$('.porder').text(order_array);
});
});
</script>
</body>
</html>
Try this code for columns order store in localStorage.
//For localstorage
$('#tblReg').dragtable({
persistState: function(table) {
if (!window.localStorage) return;
var ss = window.localStorage;
table.el.find('th').each(function(i) {
if(this.id != '') {table.sortOrder[this.id]=i;}
});
ss.setItem('tableorder', JSON.stringify(table.sortOrder));
$('a.order').trigger('click');//When drop the column then button will trigger
},
restoreState: eval('(' + window.localStorage.getItem('tableorder') + ')')
});
I have done ! Please check if any mistake.
$(document).ready(function(){
//localStorage.clear();
var tblReg = $('#tblReg').attr('id');
var tblRegMaster = $('#tblRegMaster').attr('id');
processDnD(tblReg);
processDnD(tblRegMaster);
});
function processDnD(cuTable){
var tblName = cuTable;
$('#'+cuTable).find('th').each(function() {
var ctxt = $(this).text();
if(ctxt == 'First Name'){
$(this).attr('id','firstName-'+tblName);
}else if(ctxt == 'Password'){
$(this).attr('id','password'+tblName);
}else if(ctxt == 'Email'){
$(this).attr('id','iemail'+tblName);
}else if(ctxt == 'Username'){
$(this).attr('id','userName'+tblName);
}else if(ctxt == 'Last Name'){
$(this).attr('id','lastName'+tblName);
}else if(ctxt == '#'){
$(this).attr('id','slNo'+tblName);
}else if(ctxt == 'Phone'){
$(this).attr('id','phone'+tblName);
}else if(ctxt == 'PO Number'){
$(this).attr('id','pono'+tblName);
}else if(ctxt == 'Shipper'){
$(this).attr('id','shipperName'+tblName);
}else if(ctxt == 'Status'){
$(this).attr('id','cuStatus'+tblName);
}else if(ctxt == 'Booking Line'){
$(this).attr('id','BookingLine'+tblName);
}else if(ctxt == 'Access Mode'){
$(this).attr('id','AccessMode'+tblName);
}else if(ctxt == 'Container No'){
$(this).attr('id','ContainerNo'+tblName);
}
})
$('#'+cuTable).dragtable({
persistState: function(table) {
if (!window.localStorage) return;
var ss = window.localStorage;
table.el.find('th').each(function(i) {
if(this.id != '') {table.sortOrder[this.id]=i;}
});
ss.setItem('setTableOrder-'+tblName, JSON.stringify(table.sortOrder));
},
restoreState: eval('(' + window.localStorage.getItem('setTableOrder-'+tblName) + ')')
});
$('#'+cuTable).each(function(){
$(this).dragtable({
placeholder: 'dragtable-col-placeholder',
items: 'thead th:not(.notdraggable):not(:has(.dragtable-drag-handle)), .dragtable-drag-handle',
appendTarget: $(this).parent(),
scroll: true
})
});
}
Related
Unfortunately I have no experience with javascript and just copied the html table search from https://speedysense.com/filter-html-table-using-javascript/ to a local html file. The search works but I need to extend the code to support logical search operators like || and && to implement AND and OR search functionality. Has anybody the knowledge to let me know the required adaptions to the code:
<!DOCTYPE html>
<html lang="en-US">
<head>
<title>JavaScript Table Filter Search</title>
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet">
<style type="text/css">
h3 span {
font-size: 22px;
}
h3 input.search-input {
width: 300px;
margin-left: auto;
float: right
}
.mt32 {
margin-top: 32px;
}
</style>
</head>
<body class="mt32">
<div class="container">
<h3>
<span>JavaScript Filter Table Data</span>
<input type="search" placeholder="Search..." class="form-control search-input" data-table="customers-list"/>
</h3>
<table class="table table-striped mt32 customers-list">
<thead>
<tr>
<th>Customer ID</th>
<th>Name</th>
<th>Email</th>
<th>Postal Code</th>
<th>Country</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>Ana Trujillo</td>
<td>Ana.trujillo#gmail.com</td>
<td>050214</td>
<td>Germany</td>
</tr>
<tr>
<td>2</td>
<td>Antonio Moreno</td>
<td>antoniomoreno2#gmail.com</td>
<td>12209</td>
<td>Mexico</td>
</tr>
<tr>
<td>3</td>
<td>Maria Anders</td>
<td>mariaanders#yahoo.com</td>
<td>05021</td>
<td>Germany</td>
</tr>
<tr>
<td>4</td>
<td>Thomas Hardy</td>
<td>hardythomas.90#gmail.com</td>
<td>WA1 1DP</td>
<td>United Kingdom</td>
</tr>
<tr>
<td>5</td>
<td>Christina Berglund</td>
<td>christina#outlook.com</td>
<td>S-958 22</td>
<td>Sweden</td>
</tr>
<tr>
<td>6</td>
<td>Davolio Nancy</td>
<td>nancy.davolio#gmail.com</td>
<td>810025</td>
<td>India</td>
</tr>
<tr>
<td>7</td>
<td>Fuller Andrew</td>
<td>andrew.10#yahoo.com</td>
<td>W23 458</td>
<td>United State</td>
</tr>
<tr>
<td>8</td>
<td>Leverling Janet</td>
<td>leverling.j#gmail.com</td>
<td>T5A 0B5</td>
<td>Canada</td>
</tr>
</tbody>
</table>
</div>
<script>
(function(document) {
'use strict';
var TableFilter = (function(myArray) {
var search_input;
function _onInputSearch(e) {
search_input = e.target;
var tables = document.getElementsByClassName(search_input.getAttribute('data-table'));
myArray.forEach.call(tables, function(table) {
myArray.forEach.call(table.tBodies, function(tbody) {
myArray.forEach.call(tbody.rows, function(row) {
var text_content = row.textContent.toLowerCase();
var search_val = search_input.value.toLowerCase();
row.style.display = text_content.indexOf(search_val) > -1 ? '' : 'none';
});
});
});
}
return {
init: function() {
var inputs = document.getElementsByClassName('search-input');
myArray.forEach.call(inputs, function(input) {
input.oninput = _onInputSearch;
});
}
};
})(Array.prototype);
document.addEventListener('readystatechange', function() {
if (document.readyState === 'complete') {
TableFilter.init();
}
});
})(document);
</script>
</body>
</html>
Maybe with a little explanation how this works to gain more knowledge about the functionality of the code extension!?
Thank you for your support!
Best regards
Frank
I am using a data table similar as.
$(document).ready(function() {
var table = $("#example").DataTable({
"order": [ 1, "asc" ],
// "lengthMenu": [[ 100, 200, 500,-1], [ 100, 200, 500,'All']],
"pageLength": -1,
"lengthChange": false,
"bFilter": "false",
"searchable": false,
orderCellsTop: true,
"bPaginate": false,
"bInfo": false
});
$('.filterRow th').each( function (i) {
var title = $(this).text();
var select = $('<select><option value="">All</option></select>')
.appendTo( $(this).empty() )
.on( 'change', function () {
var term = $(this).val();
table.column( i ).search(term, false, false ).draw();
} );
let includedArr = [];
let colData = table.column( i ).data().unique().sort().each( function ( d, j ) {
if(d != ""){
d = d.replace("<del>","").replace("</del>","");
if( $.inArray(d, includedArr) < 0 ) {
select.append( '<option value="'+d+'">'+d+'</option>' );
includedArr.push = d;
}
}
});
} );
} );
<link rel="stylesheet" href="https://cdn.datatables.net/1.10.22/css/jquery.dataTables.min.css">
<table id="example" class="display" style="width:100%">
<tbody>
<tr>
<td>N</td>
<td>101</td>
<td>1</td>
<td>01</td>
<td>10</td>
<td>20</td>
</tr>
<tr>
<td>N</td>
<td>102</td>
<td>1</td>
<td>02</td>
<td>(20)</td>
<td>20</td>
</tr>
<tr>
<td>N</td>
<td>103</td>
<td>1</td>
<td>03</td>
<td>
<del>10</del>
</td>
<td>20</td>
</tr>
</tbody>
<thead>
<tr>
<th rowspan="2">Bldg</th>
<th rowspan="2">Unit</th>
<th rowspan="2">Floor</th>
<th rowspan="2">Stack</th>
<th colspan="2">
Floor Level
</th>
</tr>
<tr>
<th>Floor 1</th>
<th>Floor 2</th>
</tr>
<tr class="filterRow">
<th></th>
<th></th>
<th></th>
<th></th>
<th></th>
<th></th>
</tr>
</thead>
</table>
<script src="https://code.jquery.com/jquery-3.5.1.js"></script>
<script src="https://cdn.datatables.net/1.10.22/js/jquery.dataTables.min.js"></script>
You can run the code and check on the select option of Floor 1 column, currently there it is showing double 10 option. But, it should have only one. Actually, there are this two options: 10 and '10'. Because of this del tag it considered as two options, however, I want to show just 10.
So, I tried by removing <del> tag but still, it is showing 3 options on the select field.
I'm trying to create a stat table for the hockey team I work with. We have certain metrics we want to hit for certain categories, such as we want to take >30 shots but only allow < 25 shots against; we want to take less than 3 penalties but draw more than 3, etc. Here is the table with just 2 games as input:
<body>
<header>2019-20 Team Stats</header>
<main>
<table class="table table-hover">
<thead>
<tr>
<th>Game</th>
<th>Score</th>
<th id="goal-f">GF</th>
<th id="goal-a">GA</th>
<th id="shot-f">Shots For</th>
<th id="shot-a">Shots Against</th>
<th>Shot %</th>
<th id="pen-t">Pen Taken</th>
<th id="pen-d">Pen Drawn</th>
<th>PP %</th>
<th>PK %</th>
<th id="fo-p">Face-offs</th>
<th>Hits</th>
<th id="blk">BS</th>
<th id="take-a">TA</th>
<th id="odd-man">OMA</th>
<th id="eozp">Extended OZP</th>
<th id="chance-f">CF</th>
<th id="chance-a">CA</th>
<th>Chance +/-</th>
<th id="turn-o">TO</th>
</tr>
</thead>
<tbody>
<tr>
<td>10/11/19 at Boston College</td>
<td>3-5</td> <!--Score-->
<td>3</td><!--GF-->
<td>5</td><!--GA-->
<td>26</td><!--Shots For-->
<td>28</td><!--Shots Against-->
<td>.000</td><!--Shot %-->
<td class="to-num">5</td><!--Pen Taken-->
<td>4</td><!--Pen Drawn-->
<td>33%</td><!--FO%-->
<td>40%</td><!--PP%-->
<td>100%</td><!--PK%-->
<td>9</td><!--Hits-->
<td>11</td><!--BS-->
<td>7</td><!--TA-->
<td>10</td><!--OMA-->
<td>0</td><!--OZP-->
<td>13</td><!--CF-->
<td>17</td><!--CA-->
<td>-4</td><!--C +/1-->
<td>12</td><!--TO-->
</tr>
<tr>
<td>10/12/19 at Merrimack</td>
<td>11-6</td> <!--Score-->
<td>11</td><!--GF-->
<td>6</td><!--GA-->
<td>26</td><!--Shots For-->
<td>22</td><!--Shots Against-->
<td>.000</td><!--Shot %-->
<td>3</td><!--Pen Taken-->
<td>6</td><!--Pen Drawn-->
<td>64%</td><!--FO%-->
<td>50%</td><!--PP%-->
<td>100%</td><!--PK%-->
<td>9</td><!--Hits-->
<td>14</td><!--BS-->
<td>6</td><!--TA-->
<td>11</td><!--OMA-->
<td>2</td><!--OZP-->
<td>22</td><!--CF-->
<td>14</td><!--CA-->
<td>+8</td><!--C +/1-->
<td>18</td><!--TO-->
</tr>
</tbody>
</table>
</main>
Essentially, I've tried to parseInt the .to-num class from a string to an integer, then if that integer is < or > 3, add either a 'negative' or 'positive' class, which will then change the font color from black to red or green.
for (var i = 0; i < $(".to-num").length; i++) {
var outcome = parseInt($(".to-num")[i]);
if (outcome > 3) {
$(".to-num").addClass("negative");
} else if (outcome < 3) {
$(".to-num").addClass("positive");
}
}
Here's a CodePen to my HTML, CSS and JS: https://codepen.io/emilyengelnatzke/pen/qBNOQZe
You need to set the class back on the same same element. As it is, you are setting the class on all elements each time. Also, you need a call to innerText or textContent before your parse
You can do:
$(".to-num").each(function() {
var outcome = parseInt(this.innerText);
if (outcome > 3) {
this.classList.add("negative");
} else if (outcome < 3) {
this.classList.add("positive");
}
});
The easiest way to achieve this is as follows:
// select all elements with the class-name of 'to-num', and
// call jQuery's addClass() method on each element of that
// collection:
$('.to-num').addClass(function() {
// here we return a class-name as a result of this conditional
// operator; if the parsed-value of the current element's text
// is greater than 3 we return the 'negative' class-name,
// otherwise we return 'positive':
return parseInt($(this).text().trim(), 10) > 3 ? 'negative' : 'positive';
});
$('.to-num').addClass(function() {
return parseInt($(this).text().trim(), 10) > 3 ? 'negative' : 'positive';
});
*,
::before,
::after {
box-sizing: border-box;
margin: 0;
padding: 0;
}
table {
border-collapse: collapse;
}
tbody tr:nth-child(odd) {
background-color: #dde;
}
th,
td {
background-color: transparent;
}
td.negative {
color: red;
}
td.positive {
color: green;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<header>
<h1>2019-20 Team Stats</h1>
</header>
<main>
<table class="table table-hover">
<thead>
<tr>
<th>Game</th>
<th>Score</th>
<th id="goal-f">GF</th>
<th id="goal-a">GA</th>
<th id="shot-f">Shots For</th>
<th id="shot-a">Shots Against</th>
<th>Shot %</th>
<th id="pen-t">Pen Taken</th>
<th id="pen-d">Pen Drawn</th>
<th>PP %</th>
<th>PK %</th>
<th id="fo-p">Face-offs</th>
<th>Hits</th>
<th id="blk">BS</th>
<th id="take-a">TA</th>
<th id="odd-man">OMA</th>
<th id="eozp">Extended OZP</th>
<th id="chance-f">CF</th>
<th id="chance-a">CA</th>
<th>Chance +/-</th>
<th id="turn-o">TO</th>
</tr>
</thead>
<tbody>
<tr>
<td><time date="2019-10-11">10/11/19</time>
<span class="location">Boston College</span></td>
<td>3-5</td>
<!--Score-->
<td>3</td>
<!--GF-->
<td>5</td>
<!--GA-->
<td>26</td>
<!--Shots For-->
<td>28</td>
<!--Shots Against-->
<td>.000</td>
<!--Shot %-->
<td class="to-num">5</td>
<!--Pen Taken-->
<td>4</td>
<!--Pen Drawn-->
<td>33%</td>
<!--FO%-->
<td>40%</td>
<!--PP%-->
<td>100%</td>
<!--PK%-->
<td>9</td>
<!--Hits-->
<td>11</td>
<!--BS-->
<td>7</td>
<!--TA-->
<td>10</td>
<!--OMA-->
<td>0</td>
<!--OZP-->
<td>13</td>
<!--CF-->
<td>17</td>
<!--CA-->
<td>-4</td>
<!--C +/1-->
<td>12</td>
<!--TO-->
</tr>
<tr>
<td><time date="2019-10-12">10/12/19</time>
<span class="location">Merrimack</span></td>
<td>11-6</td>
<!--Score-->
<td>11</td>
<!--GF-->
<td>6</td>
<!--GA-->
<td>26</td>
<!--Shots For-->
<td>22</td>
<!--Shots Against-->
<td>.000</td>
<!--Shot %-->
<td class="to-num">3</td>
<!--Pen Taken-->
<td>6</td>
<!--Pen Drawn-->
<td>64%</td>
<!--FO%-->
<td>50%</td>
<!--PP%-->
<td>100%</td>
<!--PK%-->
<td>9</td>
<!--Hits-->
<td>14</td>
<!--BS-->
<td>6</td>
<!--TA-->
<td>11</td>
<!--OMA-->
<td>2</td>
<!--OZP-->
<td>22</td>
<!--CF-->
<td>14</td>
<!--CA-->
<td>+8</td>
<!--C +/1-->
<td>18</td>
<!--TO-->
</tr>
</tbody>
</table>
</main>
We could, of course, easily achieve the same result using plain JavaScript:
// caching all elements in the document that include the class-name
// of 'to-num':
const collection = document.querySelectorAll('.to-num'),
// defining a named function to handle the addition of
// relevant class-names; the first three arguments
// ('el', 'index', 'arr') are passed automatically from
// the use of NodeList.prototype.forEach(); here we also
// declare the argument 'gt' ('greater-than') with a
// default value of 3 (which can be overridden by the
// author/user):
isGreaterThan = (el, index, arr, gt = 3) => {
// here we use the same conditional operator as above to
// determine which of the two class-names to use:
let newClass = parseInt(el.textContent.trim(), 10) > gt ? 'negative' : 'positive';
// and here we use the Element.classList API to add that
// class-name to the current element-node of the NodeList
// over which we're iterating:
el.classList.add(newClass);
};
// using NodeList.prototype.forEach() to iterate over the
// NodeList we cached earlier, calling the isGreaterThan()
// function on all elements in the NodeList:
collection.forEach(isGreaterThan);
const collection = document.querySelectorAll('.to-num'),
isGreaterThan = (el, index, arr, gt = 3) => {
let newClass = parseInt(el.textContent.trim(), 10) > gt ? 'negative' : 'positive';
el.classList.add(newClass);
};
collection.forEach(isGreaterThan);
*,
::before,
::after {
box-sizing: border-box;
margin: 0;
padding: 0;
}
table {
border-collapse: collapse;
}
tbody tr:nth-child(odd) {
background-color: #dde;
}
th,
td {
background-color: transparent;
}
td.negative {
color: red;
}
td.positive {
color: green;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<header>
<h1>2019-20 Team Stats</h1>
</header>
<main>
<table class="table table-hover">
<thead>
<tr>
<th>Game</th>
<th>Score</th>
<th id="goal-f">GF</th>
<th id="goal-a">GA</th>
<th id="shot-f">Shots For</th>
<th id="shot-a">Shots Against</th>
<th>Shot %</th>
<th id="pen-t">Pen Taken</th>
<th id="pen-d">Pen Drawn</th>
<th>PP %</th>
<th>PK %</th>
<th id="fo-p">Face-offs</th>
<th>Hits</th>
<th id="blk">BS</th>
<th id="take-a">TA</th>
<th id="odd-man">OMA</th>
<th id="eozp">Extended OZP</th>
<th id="chance-f">CF</th>
<th id="chance-a">CA</th>
<th>Chance +/-</th>
<th id="turn-o">TO</th>
</tr>
</thead>
<tbody>
<tr>
<td><time date="2019-10-11">10/11/19</time>
<span class="location">Boston College</span></td>
<td>3-5</td>
<!--Score-->
<td>3</td>
<!--GF-->
<td>5</td>
<!--GA-->
<td>26</td>
<!--Shots For-->
<td>28</td>
<!--Shots Against-->
<td>.000</td>
<!--Shot %-->
<td class="to-num">5</td>
<!--Pen Taken-->
<td>4</td>
<!--Pen Drawn-->
<td>33%</td>
<!--FO%-->
<td>40%</td>
<!--PP%-->
<td>100%</td>
<!--PK%-->
<td>9</td>
<!--Hits-->
<td>11</td>
<!--BS-->
<td>7</td>
<!--TA-->
<td>10</td>
<!--OMA-->
<td>0</td>
<!--OZP-->
<td>13</td>
<!--CF-->
<td>17</td>
<!--CA-->
<td>-4</td>
<!--C +/1-->
<td>12</td>
<!--TO-->
</tr>
<tr>
<td><time date="2019-10-12">10/12/19</time>
<span class="location">Merrimack</span></td>
<td>11-6</td>
<!--Score-->
<td>11</td>
<!--GF-->
<td>6</td>
<!--GA-->
<td>26</td>
<!--Shots For-->
<td>22</td>
<!--Shots Against-->
<td>.000</td>
<!--Shot %-->
<td class="to-num">3</td>
<!--Pen Taken-->
<td>6</td>
<!--Pen Drawn-->
<td>64%</td>
<!--FO%-->
<td>50%</td>
<!--PP%-->
<td>100%</td>
<!--PK%-->
<td>9</td>
<!--Hits-->
<td>14</td>
<!--BS-->
<td>6</td>
<!--TA-->
<td>11</td>
<!--OMA-->
<td>2</td>
<!--OZP-->
<td>22</td>
<!--CF-->
<td>14</td>
<!--CA-->
<td>+8</td>
<!--C +/1-->
<td>18</td>
<!--TO-->
</tr>
</tbody>
</table>
</main>
...As a follow up questions, would I need to repeat that for each category? I.e "shots for", "shots against", etc.? Or is there more of a global option?
OP's comment to another answer.
With regards to the above comment I'd simply add some custom data-* attributes, in this case perhaps data-boundary along with data-above and data-below to identify the class-names to apply if the value of the cell is above, or below, that boundary; for example:
// here we select all <th> elements with the 'data-boundary'
// attribute, and use the each() method to iterate over that
// collection:
$('th[data-boundary]').each(function(index, elem) {
// here we use a mostly native JavaScript approach for
// simplicity; the boundary we find by first using the
// Element.dataset API to retrieve the value of the
// data-boundary attribute, that is passed into the
// parseInt() function (along with the radix of 10, to
// ensure a base-10/decimal number); if parsing results
// in a false/falsey value we instead use 0 (zero is itself
// a falsey value, so this is a mild sanity-check for that
// result):
const boundary = parseInt(elem.dataset.boundary.trim(), 10) || 0,
// we use the Element.dataset API to retrieve the relevant
// class-names:
aboveClass = elem.dataset.above,
belowClass = elem.dataset.below,
// we retrieve the cellIndex of the current element
// (note that this can be problematic if the `colspan`
// attribute is used) from the HTMLTableHeaderCellElement
// (also available to HTMLTableCellElement nodes):
column = elem.cellIndex,
// here we use jQuery - although document.querySelectorAll
// could have been used just as easily - to retrieve all
// <td> elements that match the :nth-child() pseudo-class
// selector within <tr> elements and within the <tbody>
// element; we use 'column + 1' because JavaScript is
// zero-based whereas CSS is 1-based; note that we're also
// wrapping this CSS selector in a template-literal string
// in order to avoid string-concatenation with the
// variable, here we simply use the variable within the
// string inside of a '${ ...JavaScript here... }':
cells = $(`tbody tr td:nth-child(${ column + 1 })`);
// we iterate over the cells here as we did in our first
// example:
cells.addClass(function() {
return parseInt(this.textContent.trim(), 10) > boundary ? aboveClass : belowClass;
});
});
$('th[data-boundary]').each(function(index, elem) {
const boundary = parseInt(elem.dataset.boundary.trim(), 10) || 0,
aboveClass = elem.dataset.above,
belowClass = elem.dataset.below,
column = elem.cellIndex,
cells = $(`tbody tr td:nth-child(${ column + 1 })`);
cells.addClass(function() {
return parseInt(this.textContent.trim(), 10) > boundary ? aboveClass : belowClass;
});
});
*,
::before,
::after {
box-sizing: border-box;
margin: 0;
padding: 0;
}
table {
border-collapse: collapse;
}
tbody tr:nth-child(odd) {
background-color: #dde;
}
th,
td {
background-color: transparent;
}
td.negative {
color: red;
}
td.positive {
color: green;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<header>
<h1>2019-20 Team Stats</h1>
</header>
<main>
<table class="table table-hover">
<thead>
<tr>
<th>Game</th>
<th>Score</th>
<th id="goal-f">GF</th>
<th id="goal-a">GA</th>
<th id="shot-f" data-boundary="30" data-above="positive" data-below="negative">Shots For</th>
<th id="shot-a" data-boundary="25" data-above="negative" data-below="positive">Shots Against</th>
<th>Shot %</th>
<th id="pen-t" data-boundary="3" data-above="negative" data-below="positive">Pen Taken</th>
<th id="pen-d">Pen Drawn</th>
<th>PP %</th>
<th>PK %</th>
<th id="fo-p">Face-offs</th>
<th>Hits</th>
<th id="blk">BS</th>
<th id="take-a">TA</th>
<th id="odd-man">OMA</th>
<th id="eozp">Extended OZP</th>
<th id="chance-f">CF</th>
<th id="chance-a">CA</th>
<th>Chance +/-</th>
<th id="turn-o">TO</th>
</tr>
</thead>
<tbody>
<tr>
<td><time date="2019-10-11">10/11/19</time>
<span class="location">Boston College</span></td>
<td>3-5</td>
<!--Score-->
<td>3</td>
<!--GF-->
<td>5</td>
<!--GA-->
<td>26</td>
<!--Shots For-->
<td>28</td>
<!--Shots Against-->
<td>.000</td>
<!--Shot %-->
<td class="to-num">5</td>
<!--Pen Taken-->
<td>4</td>
<!--Pen Drawn-->
<td>33%</td>
<!--FO%-->
<td>40%</td>
<!--PP%-->
<td>100%</td>
<!--PK%-->
<td>9</td>
<!--Hits-->
<td>11</td>
<!--BS-->
<td>7</td>
<!--TA-->
<td>10</td>
<!--OMA-->
<td>0</td>
<!--OZP-->
<td>13</td>
<!--CF-->
<td>17</td>
<!--CA-->
<td>-4</td>
<!--C +/1-->
<td>12</td>
<!--TO-->
</tr>
<tr>
<td><time date="2019-10-12">10/12/19</time>
<span class="location">Merrimack</span></td>
<td>11-6</td>
<!--Score-->
<td>11</td>
<!--GF-->
<td>6</td>
<!--GA-->
<td>26</td>
<!--Shots For-->
<td>22</td>
<!--Shots Against-->
<td>.000</td>
<!--Shot %-->
<td class="to-num">3</td>
<!--Pen Taken-->
<td>6</td>
<!--Pen Drawn-->
<td>64%</td>
<!--FO%-->
<td>50%</td>
<!--PP%-->
<td>100%</td>
<!--PK%-->
<td>9</td>
<!--Hits-->
<td>14</td>
<!--BS-->
<td>6</td>
<!--TA-->
<td>11</td>
<!--OMA-->
<td>2</td>
<!--OZP-->
<td>22</td>
<!--CF-->
<td>14</td>
<!--CA-->
<td>+8</td>
<!--C +/1-->
<td>18</td>
<!--TO-->
</tr>
</tbody>
</table>
</main>
References:
HTML:
Custom data-* attributes.
JavaScript:
Arrow functions.
Conditional (ternary) Operator.
document.querySelectorAll().
HTMLOrForeignElement.dataset API.
HTMLTableCellElement.
NodeList.prototype.forEach().
Template Literal Strings.
String.prototype.trim().
jQuery:
addClass().
text().
I am trying to remove matched record from both table if i click remove. Here matching except last column only because last column remove button. My code is not working: if I click remove all matched tr removing but I want which row I have clicked remove button in both tables that matched row only remove. How can I do it?
Code: https://jsfiddle.net/d4yzrtwn/3/
$(function(){
$('.remove').on('click', function(e){
$('#T1 tbody tr').each(function(){
var row = $(this);
var left_cols = $(this).find("td").not(':last');
$('#T2 tbody tr').each(function(){
var right_cols = $(this).find("td").not(':last');
if(left_cols.html() == right_cols.html()) {
$(this).closest('tr').remove();
}
});
$(this).closest('tr').remove();
});
});
});
Compare html content based on selected row's table with correspondent table.
Selection is dynamic, meaning works visa-versa and restricts remove on non-matching records.
$(function() {
$('.remove').click(function() {
let clicked_row = $(this).closest('tr');
let clicked_table = clicked_row.closest('table tbody').find('tr');
clicked_table.each(function() {
if (clicked_row.closest('table').attr('id') === 'T1') {
opponent_table = $('#T2 tbody tr');
} else {
opponent_table = $('#T1 tbody tr');
}
opponent_table.each(function() {
if ($(this).html() === clicked_row.html()) {
$(this).remove();
clicked_row.remove();
}
});
});
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<table id="T1" border='1'>
<thead>
<tr>
<th>First Name</th>
<th>Middle Name</th>
<th>Last Name</th>
<th>Suffix</th>
</tr>
</thead>
<tbody>
<tr>
<td>12</td>
<td>34</td>
<td>56</td>
<td><span class="remove">Remove</span></td>
</tr>
<tr>
<td>12</td>
<td>84</td>
<td>96</td>
<td><span class="remove">Remove</span></td>
</tr>
<tr>
<td>bat</td>
<td>man</td>
<td>11</td>
<td><span class="remove">Remove</span></td>
</tr>
</tbody>
</table>
<br>
<table id="T2" border='1'>
<thead>
<tr>
<th>First Name</th>
<th>Middle Name</th>
<th>Last Name</th>
<th>Suffix</th>
</tr>
</thead>
<tbody>
<tr>
<td>12</td>
<td>34</td>
<td>56</td>
<td><span class="remove">Remove</span></td>
</tr>
<tr>
<td>bat</td>
<td>man</td>
<td>11</td>
<td><span class="remove">Remove</span></td>
</tr>
<tr>
<td>james</td>
<td>bond</td>
<td>007</td>
<td><span class="remove">Remove</span></td>
</tr>
<tr>
<td>12</td>
<td>34</td>
<td>56</td>
<td><span class="remove">Remove</span></td>
</tr>
</tbody>
</table>
jsfiddle here: https://jsfiddle.net/debendraoli/qvy0dLfh/33/
#cinan
This code will do the job. It's more clear and readable. If you have any further questions please let me know.
$(function(){
$('.remove').on('click', function(e) {
var $removedRow = $(this).closest('tr');
var removedRowHtml = $removedRow.html();
var $clickedTable = $(this).closest('table');
var $anotherTable = $('table').not($clickedTable);
$('tr', $anotherTable).each(function(k, entry) {
if ($(entry).html() === removedRowHtml) {
$(entry).remove();
}
});
$removedRow.remove();
});
});
You can check it here as well: https://codepen.io/anon/pen/RdpMQP
$(function(){
$('.remove').on('click', function(e){
var content = $(e.currentTarget).closest("tr").text().trim();
$("#T1 tbody tr, #T2 tbody tr").each(function(e){
if($(this).text().trim() === content){
$(this).remove();
}
});
});
});
change your script to this. you don't have to do that all checks
I want to search do search functionality on multiple colums using bootstrap table by using javascript guide me. Here i am showing my javascript code used for search on first column. Guide me that how t use more columns using javascript.
$("#search").on("keyup",function(){
var value=$(this).val();
$("table tr").each(function(index){
if (index!==0){
$row = $(this);
var id= $row.find("td:first").text();
if (id.indexOf(value)!==0){
$row.hide();
}
else{
$row.show();
}
}
});
});
HTML
<input type="text" name="search" id="search" placeholder="Search">
<table data-toggle="table" data-sort-name="name" data-sort-order="asc" >
<thead>
<tr>
<th data-field="name" data-sortable="true">Name</th>
<th data-field="address" data-sortable="true">Address</th>
<th data-field="birthdate" data-sortable="true">Birth Date</th>
<th>Gender</th>
<th data-field="hobby" data-sortable="true">Hobbies</th>
<th>Action</th>
</tr>
</thead>
Try this,
Without your full html table, I can only guess what it looks like and try to create something that would work
$("#search").on("keyup", function() {
var value = $(this).val().toLowerCase();
console.clear()
$("table tr").each(function(index) {
if (index !== 0) {
$row = $(this);
$row.find("td").each(function(i, td) {
var id = $(td).text().toLowerCase();
console.log(id + " | " + value + " | " + id.indexOf(value))
if (id.indexOf(value) !== -1) {
$row.show();
return false;
} else {
$row.hide();
}
})
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" name="search" id="search" placeholder="Search">
<table data-toggle="table" data-sort-name="name" data-sort-order="asc">
<thead>
<tr>
<th data-field="name" data-sortable="true">Name</th>
<th data-field="address" data-sortable="true">Address</th>
<th data-field="birthdate" data-sortable="true">Birth Date</th>
<th>Gender</th>
<th data-field="hobby" data-sortable="true">Hobbies</th>
<th>Action</th>
</tr>
</thead>
<tbody>
<tr>
<td>Peter</td>
<td>Street 123</td>
<td>03 may</td>
<td>Male</td>
<td>Code</td>
<td>None</td>
</tr>
<tr>
<td>Emma</td>
<td>Street 123</td>
<td>03 may</td>
<td>Female</td>
<td>Code</td>
<td>None</td>
</tr>
</tbody>
</table>