bootstrap table custom search - javascript

I have following table:
<table>
<tr>
<th>Number</th>
<th>Name</th>
</tr>
<tr>
<td>200.10.1234</td>
<td>Maria Anders</td>
</tr>
<tr>
<td>202.10.9234</td>
<td>Francisco Chang</td>
</tr>
</table>
JS:
$('#table').bootstrapTable({
pagination: true,
search: true,
});
I want to implement following search behaviour: if the user search for "2001" or "200.1" then the first entry shall be shown. If the user search for "10.1234" or "101234" then again the first entry shall be shown.
Does anybody have an idea how to implement this?
Here is the doc: http://bootstrap-table.wenzhixin.net.cn/documentation/

You may do as follows;
var ftds = document.querySelectorAll("tr > td:first-child"),
choose = document.getElementById("choose");
choose.addEventListener("change", function isChosen(e) {
ftds.forEach(function(ftd) {
var dotless = ftd.textContent.replace(/\./g, "");
ftd.parentElement.style.backgroundColor = ~ftd.textContent.indexOf(e.target.value) ||
~dotless.indexOf(e.target.value) ? "green" : "white";
});
});
<table>
<tr>
<th>Number</th>
<th>Name</th>
</tr>
<tr>
<td>200.10.1234</td>
<td>Maria Anders</td>
</tr>
<tr>
<td>202.10.9234</td>
<td>Francisco Chang</td>
</tr>
</table>
<label for="choose">Chose ID:</label>
<input id="choose" required>
I was a little lazy to add a button but striking tab or clicking somewhere out of the input element should do.
Hint: ~(-1) === 0; tilde changes -1 to 0 (falsey value)
OK lets carry on with a Bootstrap example. This time we will define a class for the row that contains the number we search and add it to our CSS file. Let it be something like;
.found {
outline: #2E8B57 solid 1px;
background-color: #98FB98;
}
Now if we check all first <td> elements (which contains the number data) in each row. If it doesn't contain we will remove the .found class from the parentElement.classList (if the parent element's class list doesn't have it no error will be thrown) if we find what we are looking for then we will add .found class to the parent element's class list.
Very simple..
var ftds = document.querySelectorAll("tr > td:first-child"),
choose = document.getElementById("choose");
choose.addEventListener("change", function isChosen(e) {
ftds.forEach(function(ftd) {
var dotless = ftd.textContent.replace(/\./g, "");
~ftd.textContent.indexOf(e.target.value) ||
~dotless.indexOf(e.target.value) ? ftd.parentElement.classList.add("found")
: ftd.parentElement.classList.remove("found");
});
});
.found {
outline: #2E8B57 solid 1px;
background-color: #98FB98;
}
<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="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
<table class="table table-hover">
<thead>
<tr>
<th>Number</th>
<th>First Name</th>
<th>Last Name</th>
</tr>
</thead>
<tbody>
<tr>
<td>200.10.1234</td>
<td>Maria</td>
<td>Anders</td>
</tr>
<tr>
<td>202.10.9234</td>
<td>Fransisco</td>
<td>Chang</td>
</tr>
<tr>
<td>203.10.5678</td>
<td>Fabrio</td>
<td>Donetti</td>
</tr>
</tbody>
</table>
</div>
<label for="choose">Search ID:</label>
<input id="choose" required>
</body>
</html>

#Lahmacun, I've linked a codeply project that implements the bootstrap table. All of this code can be found in the documentation for the website that you've provided. In fact, the search functionality you're looking for is already baked into it; no need to write any custom code. You just have to call it by setting the data-search attribute to true.
HTML Code:
<table id="table" data-url="" data-search="true" data-show-refresh="true" data-show-toggle="true" data-show-columns="true">
</table>
JavaScript Code:
$('#table').bootstrapTable({
columns: [{
field: 'number',
title: 'Number'
}, {
field: 'name',
title: 'Name'
}],
data: [{
id: 1,
number: '200.10.1234',
name: 'Maria Anders'
}, {
id: 2,
number: '202.10.9234',
name: 'Francisco Chang'
}]
});

Related

Display "no results found" if there is no matching search text input on the table

I saw this block of code from w3schools and it works perfectly fine. My only issue is that, if the inputted text is not present on the table, it doesn't display anything.
Here's the script code:
$(document).ready(function() {
$('#searchBar').on('keyup', function() {
var value = $(this).val().toLowerCase();
$('#tableData tr').filter(function() {
$(this).toggle($(this).text().toLowerCase().indexOf(value) > -1)
});
});
});
Here's the link to the w3schools article that I am talking about:
https://www.w3schools.com/bootstrap/bootstrap_filters.asp
I'd like to display a text saying "No results found" if there are no search results.
Here my solution for your problem I think this is the optimal solution for your problem.
Here the HTML which I get from the link you provided of w3school I added here a new row in HTML , little style and some conditional line in the JS code
<!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="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
<style>
.no-data {
display: none;
text-align: center;
}
</style>
</head>
<body>
<div class="container">
<h2>Filterable Table</h2>
<p>Type something in the input field to search the table for first names, last names or emails:</p>
<input class="form-control" id="myInput" type="text" placeholder="Search..">
<br>
<table class="table table-bordered table-striped">
<thead>
<tr>
<th>Firstname</th>
<th>Lastname</th>
<th>Email</th>
</tr>
</thead>
<tbody id="myTable">
<tr>
<td>John</td>
<td>Doe</td>
<td>john#example.com</td>
</tr>
<tr>
<td>Mary</td>
<td>Moe</td>
<td>mary#mail.com</td>
</tr>
<tr>
<td>July</td>
<td>Dooley</td>
<td>july#greatstuff.com</td>
</tr>
<tr>
<td>Anja</td>
<td>Ravendale</td>
<td>a_r#test.com</td>
</tr>
<tr class="no-data">
<td colspan="4">No data</td>
</tr>
</tbody>
</table>
<p>Note that we start the search in tbody, to prevent filtering the table headers.</p>
</div>
<script>
$(document).ready(function(){
$("#myInput").on("keyup", function() {
let check = true;
var value = $(this).val().toLowerCase();
$("#myTable tr").filter(function() {
$(this).toggle($(this).text().toLowerCase().indexOf(value) > -1)
if($(this).text().toLowerCase().indexOf(value) > -1){
check = false;
$('.no-data').hide();
}
});
if(check){
$('.no-data').show();
}
});
});
</script>
</body>
</html>
the new row I added in HTML for showing "No data" is here:
<tr class="no-data">
<td colspan="4">No data</td>
</tr>
style for the new row
.no-data {
display: none;
text-align: center;
}
I added a some new conditional line in JS and after adding those the JS code is :
$(document).ready(function(){
$("#myInput").on("keyup", function() {
let check = true;
var value = $(this).val().toLowerCase();
$("#myTable tr").filter(function() {
$(this).toggle($(this).text().toLowerCase().indexOf(value) > -1)
if($(this).text().toLowerCase().indexOf(value) > -1){
check = false;
$('.no-data').hide();
}
});
if(check){
$('.no-data').show();
}
});
});
Hope your problem is solved have a nice day .

How to hide a table upon page load and then display filtered data with table headers?

Upon loading my table page, I want the table to be completely hidden.When I load the page, I want to filter the data and display the headers and related data based on the selected filter.
I am able to hide the table upon page load as well as filter it.
My issue:
Although the filter works, I am having trouble displaying the headers along with the related rows when Select Location is selected.
I would like to remove the gray line that appears upon page load.
Please see the sample code here: http://live.datatables.net/milazige/6/edit
$(document).ready(function () {
// hide tbody on load
$('#example tbody').hide();
$('#example thead').hide();
var table = $('#example').DataTable({
paging: false,
searching: true,
lengthChange: false,
responsive: false,
scrollX: true,
bInfo: false,
bSort: false,
"language": {
"zeroRecords": ""
}
});
$('#table-filter').on('change', function () {
// show the tbody when the user clicks on a filter option
$('#example thead').show();
$('#example tbody').show();
table.search(this.value).draw();
});
});
.dataTables_wrapper .dataTables_filter {
padding-bottom: 16px;
display: none;
}
<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-1.11.3.min.js"></script>
<link href="https://nightly.datatables.net/css/jquery.dataTables.css" rel="stylesheet" type="text/css" />
<script src="https://nightly.datatables.net/js/jquery.dataTables.js"></script>
<meta charset=utf-8 />
</head>
<body>
<p>Select: <select id="table-filter">
<option>Location</option>
<option>Dallax, TX</option>
<option>Boston, MA</option>
<option>Sandy, UT</option>
<option>Washington, DC</option>
<option>Omaha, NE</option>
</select>
</p>
<table id="example" class="row-border stripe dataTable no-footer dtr-inline" role="grid" style=" width: 100%;"><thead>
<tr>
<th>Location</th>
<th>Name</th>
<th>Job</th>
<th>Salary</th>
</tr>
</thead><tbody>
<tr>
<td>Dallax, TX</td>
<td>test1</td>
<td>5</td>
<td>16</td>
</tr>
<tr>
<td>Boston, MA</td>
<td>test2</td>
<td>test2</td>
<td>test2</td>
</tr>
<tr>
<td>Sandy, UT</td>
<td>test3</td>
<td>test3</td>
<td>test3</td>
</tr>
<tr>
<td>Washington, DC</td>
<td>test4</td>
<td>test4</td>
<td>test4</td>
</tr>
<tr>
<td>Omaha, NE</td>
<td>test5</td>
<td>test5</td>
<td>test5</td>
</tr>
</tbody></table>

How to do a non-text based search on a datatable when a select changes

I am trying to filter the datatable column status via select when the content of the column is not a text.
What I've tried so far:
LIVE DATATABLES
Basically I tried using the search engine this way:
$('#search2').on('change', () =>
{
DT1.search($('#search2').val()).draw();
});
But as is obvious, if we compare a String with a 'colored square' there is no result.
How can I do so that if the user selects Active, only the green squares are shown and if the user selects inactive, only the red squares are shown?
Any help will be highly appreciated
Not the most optimal way I can write in a rush at late night though thought I'd provide a working solution in case no one else does.
$(document).ready(function() {
var DT1 = $('#example').DataTable({
columnDefs: [{
orderable: false,
className: 'select-checkbox',
targets: 0,
}],
select: {
style: 'os',
selector: 'td:first-child'
},
order: [
[1, 'asc']
],
dom: 'lrt'
});
$(".selectAll").on("click", function(e) {
if ($(this).is(":checked")) {
DT1.rows().select();
} else {
DT1.rows().deselect();
}
});
$('#search').on('input', () => {
DT1.search($('#search').val()).draw();
});
$('#search2').on('change', () => {
const state = $("#search2").val();
if (state === "none") {
$(".status-active").parent().parent().attr("hidden", false);
$(".status-inactive").parent().parent().attr("hidden", false);
return;
}
$(".status-" + ((state === "active") ? 'inactive' : 'active')).parent().parent().attr("hidden", true);
$(".status-" + state).parent().parent().attr("hidden", false);
});
});
body {
font: 90%/1.45em "Helvetica Neue", HelveticaNeue, Verdana, Arial, Helvetica, sans-serif;
margin: 0;
padding: 0;
color: #333;
background-color: #fff;
}
.status-active {
height: 25px;
width: 25px;
background-color: #385C0B;
margin: 0 auto;
}
.status-inactive {
height: 25px;
width: 25px;
background-color: #CC000C;
margin: 0 auto;
}
<!DOCTYPE html>
<html>
<head>
<meta name="description" content="stackoverflow" />
<script src="http://code.jquery.com/jquery-1.11.3.min.js"></script>
<link href="https://nightly.datatables.net/css/jquery.dataTables.css" rel="stylesheet" type="text/css" />
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.1.0/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-KyZXEAg3QhqLMpG8r+8fhAXLRk2vvoC2f3B09zVXn8CA5QIVfZOJ3BCsw2P0p/We" crossorigin="anonymous">
<script src="https://nightly.datatables.net/js/jquery.dataTables.js"></script>
<script type="text/javascript" charset="utf8" src="https://cdn.datatables.net/select/1.3.3/js/dataTables.select.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.1.0/dist/js/bootstrap.bundle.min.js" integrity="sha384-U1DAWAznBHeqEIlVSCgzq+c9gqGAJn5c/t99JyeKa9xxaYpSvHU5awsuZVVFIhvj" crossorigin="anonymous"></script>
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/select/1.3.3/css/select.dataTables.min.css">
<meta charset=utf-8 />
<title>DataTables - JS Bin</title>
</head>
<body>
<div class="container">
<div class="row">
<div class="form-inline">
<input id="search" title="Search" placeholder="Search" class="filter-input form-control form-control-sm m-2" type="text" name="filter-project" value="">
<select id="search2" name="expense_category" class="form-control form-control-sm m-2">
<option value="none">Select a Status</option>
<option value="active">Active</option>
<option value="inactive">Inactive</option>
</select>
</div>
<table id="example" class="display nowrap" width="100%">
<thead>
<tr>
<th class="text-center"><input type="checkbox" class="selectAll" name="selectAll" value="all"></th>
<th>Name</th>
<th>Status</th>
<th>Office</th>
<th>Age</th>
<th>Start date</th>
<th>Salary</th>
</tr>
</thead>
<tbody>
<tr>
<td></td>
<td>Tiger Nixon</td>
<td>
<div class="status-active" title="Active"></div>
</td>
<td>Edinburgh</td>
<td>61</td>
<td>2011/04/25</td>
<td>$3,120</td>
</tr>
<tr>
<td></td>
<td>Garrett Winters</td>
<td>
<div class="status-active" title="Active"></div>
</td>
<td>Edinburgh</td>
<td>63</td>
<td>2011/07/25</td>
<td>$5,300</td>
</tr>
<tr>
<td></td>
<td>Donna Snider</td>
<td>
<div class="status-inactive"></div>
</td>
<td>New York</td>
<td>27</td>
<td>2011/01/25</td>
<td>$3,120</td>
</tr>
</tbody>
</table>
</div>
</body>
</html>
Explanation
We are focusing primarily on the event handler for when the status dropdown is changed.
$('#search2').on('change', () =>
{
const state = $("#search2").val();
if (state === "none") {
$(".status-active").parent().parent().attr("hidden", false);
$(".status-inactive").parent().parent().attr("hidden", false);
return;
}
$(".status-" + ((state === "active") ? 'inactive' : 'active')).parent().parent().attr("hidden", true);
$(".status-" + state).parent().parent().attr("hidden", false);
});
First, we fetch the state of the dropdown menu and what is selected by fetching the value of the selection with .val(), this will give us either active, inactive, or none. (I made the necessary adjustment to your HTML dropdown to add these values.)
With this information, we know what type of filtering we need to do.
Updating States
If no status is selected (none) then we unhide all rows by fetching every element with the classes .status-active and .status-inactive, this is done in the following manner:
$(".status-active").parent().parent().attr("hidden", false);
The $(".status-active") fetches all rows with the active class, and gets the parent of the parent which gives us the row element itself, and sets the hidden attribute to false, making it visible.
Filtering Active/Inactive
Here is the code that actually does the filtering:
$(".status-" + ((state === "active") ? 'inactive' : 'active')).parent().parent().attr("hidden", true);
$(".status-" + state).parent().parent().attr("hidden", false);
Examining the first line more closely, there is a ternary operator which checks to see if the state is equal to active, in which case if it is, it will output inactive, or vise versa, the purpose of this is to select the opposite class attribute so we can hide it.
The second line simply fetches all rows with the state that was selected, and makes them visible.
You can use DataTables support for orthogonal data. This feature allows you to save more than one value for each cell in your table, including:
the display value
the value to use when sorting
the value to use when filtering
(Most of the time, you do not explicitly use this feature, and therefore all these values are the same as the display value.)
So, in your case, you can use the colored square as the display value, and the words "Active" and "Inactive" as the filter values.
Because you have a pre-built HTML table, you can use DataTables support for HTML 5 orthogonal values to provide the filter terms:
<td data-filter="Inactive"><div class="status-inactive"></div></td>
In the above fragment, I added the data-filter="Inactive" attribute to the <td> tag.
The following extra steps are also needed:
Because you want to combine the drop-down filter with the global text filter, you cannot provide these as two separate DT1.search() functions. Currently, these two functions will not work in combination correctly.
To handle this you can create a custom search function for the drop-down filter:
$.fn.dataTable.ext.search.push(
function( settings, searchData, index, rowData, counter ) {
console.log( searchData );
var statusFilter = $('#search2').val();
var statusCell = searchData[2] || ''; // using 'status' data from the 3rd column
return (statusFilter === '' || statusFilter === statusCell) ;
}
);
This custom search function is added to an array containing the existing search function provided out-of-the box by DataTables - this is why we use $.fn.dataTable.ext.search.push in the above code fragment.
The existing search function is combined with our custom search function for the drop-down.
We also change the related event to simply re-draw the table - which will automatically cause the array of search functions to be executed:
$('#search2').on('change', () => {
DT1.draw();
});
Here is a demo:
$(document).ready(function() {
$.fn.dataTable.ext.search.push(
function( settings, searchData, index, rowData, counter ) {
//console.log( searchData );
var statusFilter = $('#search2').val();
var statusCell = searchData[2] || ''; // using 'status' data from the 3rd column
return (statusFilter === '' || statusFilter === statusCell) ;
}
);
var DT1 = $('#example').DataTable(
{
columnDefs: [
{
orderable: false,
className: 'select-checkbox',
targets: 0,
} ],
select: {
style: 'os',
selector: 'td:first-child'
},
order: [[ 1, 'asc' ]],
dom: 'lrt'
});
$(".selectAll").on( "click", function(e) {
if ($(this).is( ":checked" )) {
DT1.rows( ).select();
} else {
DT1.rows( ).deselect();
}
});
$('#search').on('input', () => {
DT1.search($('#search').val()).draw();
});
$('#search2').on('change', () => {
DT1.draw();
});
});
<!DOCTYPE html>
<html>
<head>
<meta name="description" content="stackoverflow" />
<script src="http://code.jquery.com/jquery-1.11.3.min.js"></script>
<link href="https://nightly.datatables.net/css/jquery.dataTables.css" rel="stylesheet" type="text/css" />
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.1.0/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-KyZXEAg3QhqLMpG8r+8fhAXLRk2vvoC2f3B09zVXn8CA5QIVfZOJ3BCsw2P0p/We" crossorigin="anonymous">
<script src="https://nightly.datatables.net/js/jquery.dataTables.js"></script>
<script type="text/javascript" charset="utf8" src="https://cdn.datatables.net/select/1.3.3/js/dataTables.select.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.1.0/dist/js/bootstrap.bundle.min.js" integrity="sha384-U1DAWAznBHeqEIlVSCgzq+c9gqGAJn5c/t99JyeKa9xxaYpSvHU5awsuZVVFIhvj" crossorigin="anonymous"></script>
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/select/1.3.3/css/select.dataTables.min.css">
<meta charset=utf-8 />
<title>demo</title>
<style>
body {
font: 90%/1.45em "Helvetica Neue", HelveticaNeue, Verdana, Arial, Helvetica, sans-serif;
margin: 0;
padding: 0;
color: #333;
background-color: #fff;
}
.status-active{
height: 25px;
width: 25px;
background-color: #385C0B;
margin: 0 auto;
}
.status-inactive{
height: 25px;
width: 25px;
background-color: #CC000C;
</style>
</head>
<body>
<div class="container">
<div class="row">
<div class="form-inline">
<input id="search" title="Search" placeholder="Search" class="filter-input form-control form-control-sm m-2"
type="text" name="filter-project" value="">
<select id="search2" name="expense_category" class="form-control form-control-sm m-2">
<option value="">Select a Status</option>
<option value="Active">Active</option>
<option value="Inactive">Inactive</option>
</select>
</div>
<table id="example" class="display nowrap" width="100%">
<thead>
<tr>
<th class="text-center"><input type="checkbox" class="selectAll" name="selectAll" value="all"></th>
<th>Name</th>
<th>Status</th>
<th>Office</th>
<th>Age</th>
<th>Start date</th>
<th>Salary</th>
</tr>
</thead>
<tbody>
<tr>
<td></td>
<td>Tiger Nixon</td>
<td data-filter="Active"><div class="status-active" title="Active"></div></td>
<td>Edinburgh</td>
<td>61</td>
<td>2011/04/25</td>
<td>$3,120</td>
</tr>
<tr>
<td></td>
<td>Garrett Winters</td>
<td data-filter="Active"><div class="status-active" title="Active"></div></td>
<td>Edinburgh</td>
<td>63</td>
<td>2011/07/25</td>
<td>$5,300</td>
</tr>
<tr>
<td></td>
<td>Donna Snider</td>
<td data-filter="Inactive"><div class="status-inactive"></div></td>
<td>New York</td>
<td>27</td>
<td>2011/01/25</td>
<td>$3,120</td>
</tr>
</tbody>
</table>
</div>
</body>
</html>
Final point:
If you are populating the HTML table dynamically, then you can use the DataTables columns.render function to achieve the same effect as the HTML5 data-filter attribute.
In your case you don't need this, because your HTML table is pre-built, before you create the DataTable.

tablesorter - How to sort child rows and parent rows

I'm using tablesorter on my project with the children functionality (described here).
Here is my code:
$(function() {
$('table').tablesorter();
});
td,
th {
border: solid 2px #121E23
}
table {
border-collapse: collapse;
}
thead {
background-color: red;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
</style>
</head>
<body>
<table>
<thead>
<tr>
<th>this is column 1</th>
<th>this is column 2</th>
</tr>
</thead>
<tbody>
<tr>
<th colspan="4">TITLE 1</th>
</tr>
<tr class="tablesorter-childRow">
<td>abc</td>
<td>yolo</td>
</tr>
<tr class="tablesorter-childRow">
<td>def</td>
<td>yolo</td>
</tr>
<tr>
<th colspan="4">TITLE 2</th>
</tr>
<tr class="tablesorter-childRow">
<td>test1</td>
<td>yolo</td>
</tr>
<tr class="tablesorter-childRow">
<td>test2</td>
<td>yolo</td>
</tr>
</tbody>
</table>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.tablesorter/2.31.1/js/jquery.tablesorter.combined.min.js"></script>
</body>
</html>
By default we have this:
And if we change the sorting order of the first column (by clicking on it), we get this :
Simply because tablesorter sorts the parent rows (TITLE 1 and TITLE 2), and keeps the children rows in the same order as at the beggining.
But I would like tablesorter to also sorts the children rows, and so to get my table like this:
How can I do that ?
Thanks for your help.

handle mdl table check box

I'm using material desigin lite in my website
I have implemented this example:
http://www.getmdl.io/components/index.html#tables-section
<table class="mdl-data-table mdl-js-data-table mdl-data-table--selectable mdl-shadow--2dp">
<thead>
<tr>
<th class="mdl-data-table__cell--non-numeric">Material</th>
<th>Quantity</th>
<th>Unit price</th>
</tr>
</thead>
<tbody>
<tr>
<td class="mdl-data-table__cell--non-numeric">Acrylic (Transparent)</td>
<td>25</td>
<td>$2.90</td>
</tr>
<tr>
<td class="mdl-data-table__cell--non-numeric">Plywood (Birch)</td>
<td>50</td>
<td>$1.25</td>
</tr>
<tr>
<td class="mdl-data-table__cell--non-numeric">Laminate (Gold on Blue)</td>
<td>10</td>
<td>$2.35</td>
</tr>
</tbody>
</table>
my question is how to handle the check box in the table , they are added by the class : .mdl-data-table--selectable
there is no Id or class for them so what is the way to use them in javascript or sql server (deleting rows what i'm trying to implement)
You could check if they're are clicked with a jquery on method, why am not using the normal .click is to because of event delegation. Jquery docs do a perfect job explaining that.
Before I explain how I did it I will have a snippet that you can immediately play with under my explanation.
I basically used inspect element to look at the tables structure and it looked something like this
<tr>
<td>
<label>clickable checkbox code</label>
</td>
<td>Acrylic</td>
<td>25</td>
<td>$2.90</td>
With that information, we can do a lot. I personally used this to listen to clicks.
$(document).on("click",".mdl-checkbox__ripple-container.mdl-js-ripple-effect.mdl-ripple--center", function() { /* Code here*/ });
And with jquery parents & children methods we can achieve a lot, like read the content of all the table data with the following code in our click event listener
foo = $(this).parents().eq(2).children().text();
Or we can perhaps delete a whole row?
$(this).parents().eq(2).fadeOut();
What that would do is, look at the clicked checkbox using "this" as reference. Then go to levels up and remove a whole row.
<tr><!-- eq 2 -->
<td> <!-- eq 1 -->
<label>clickable checkbox code</label>
</td>
<td>Acrylic</td>
<td>25</td>
<td>$2.90</td>
Or we can check for the content of a specific child like this
var secondChildContent = $(this).parents().eq(2).children().eq(2).text();
Where secondChildContent will be return the content. You can always change the eq (The one after children) value to the desired child number you want. In the following case secondChildContent would return "Acrylic"
<tr>
<td> <!-- eq 1 -->
<label>clickable checkbox code</label>
</td>
<td>Acrylic</td> <!-- eq 2 -->
<td>25</td> <!-- eq 3 -->
<td>$2.90</td> <!-- eq 4 -->
$(document).ready(function() {
$(document).on("click", ".mdl-checkbox__ripple-container.mdl-js-ripple-effect.mdl-ripple--center", function() {
//Removing row
$(this).parents().eq(2).delay(500).fadeOut(300);
var secondChildContent = $(this).parents().eq(2/*child number*/).children().eq(2).text();
var allChildrenContent = $(this).parents().eq(2).children().text();
var parentID = $(this).parents().eq(2).attr('id');
//Removing table on click of first checkbox
if (parentID == "header") {
$("#mdlTable").fadeOut(1000);
$("#log").html("<b>Table removed!</b>");
} else {
//Don't pay attention to this
$("#log").html(
"<b>Second child content is: </b>" + secondChildContent +
"<br><b>All children content is: </b>" + allChildrenContent
)
}
});
});
#log,
#mdlTable {
margin: 1% 1% 1% 1%;
}
<!DOCTYPE html>
<html>
<head>
<title>Table</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<link rel="stylesheet" href="https://storage.googleapis.com/code.getmdl.io/1.0.4/material.indigo-pink.min.css">
<script src="https://storage.googleapis.com/code.getmdl.io/1.0.4/material.min.js"></script>
<link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons">
</head>
<body>
<table id="mdlTable" class="mdl-data-table mdl-js-data-table mdl-data-table--selectable mdl-shadow--2dp">
<thead>
<tr id="header">
<th class="mdl-data-table__cell--non-numeric">Material</th>
<th>Quantity</th>
<th>Unit price</th>
</tr>
</thead>
<tbody>
<tr>
<td class="mdl-data-table__cell--non-numeric">Acrylic (Transparent)</td>
<td>25</td>
<td>$2.90</td>
</tr>
<tr>
<td class="mdl-data-table__cell--non-numeric">Plywood (Birch)</td>
<td>50</td>
<td>$1.25</td>
</tr>
<tr>
<td class="mdl-data-table__cell--non-numeric">Laminate (Gold on Blue)</td>
<td>10</td>
<td>$2.35</td>
</tr>
</tbody>
</table>
<div id="log"></div>
</body>
When a checkbox is selected, the tr gets the class "is-checked" with Material Design Lite.
So your jquery can be like this:
$("table").find("tr.is-checked").each(function(){
// Do some stuff!
});
Update: Just read that the class "mdl-data-table--selectable " is being deprecated... This is the article on github
You can use this OnClick API function.
It uses like Android onClickListener, but it is for JavaScript.
TablesOnClickListener = function() {
var fun;
this.setOnClickListener = function(listener) {
fun = listener;
$(document).on("click", ".mdl-checkbox__ripple-container.mdl-js-ripple-effect.mdl-ripple--center", function() {
//$(this).parents().eq(2).delay(500).fadeOut(300);
var secondChildContent = $(this).parents().eq(2 /*child number*/ ).children().eq(2).text();
var allChildrenContent = $(this).parents().eq(2).children().text();
var parentID = $(this).parents().eq(2).attr('id');
fun({
sen: secondChildContent,
text: allChildrenContent,
id: parentID
});
});
}
How to use:
Step 1: create new TablesOnClickListener
var tocl = new TablesOnClickListener()
Step 2: set Item OnClickListener
tocl.setOnClickListener(function(data){
console.log(data);
});
Now your Tables Item Listener are all set!

Categories