I had a multidimensional array that consists of dynamic elements per subarray. What I was trying to do was construct a bootstrap table by reading the array. To explain the table format better: If my multidimensional array is mdArray = [[name1, name2, name3, name4], [name5, name6, name7]]
I wanted to create a table of 4 columns with mdArray[0], mdArray[1], mdArray[2], mdArray[3] then create an new row when next sub-array is detected with columns mdArray[4], mdArray[5], mdArray[6]. What I have tried is below. How can I achieve this? Any help is appreciated. Thanks in advance?
mdArray = [
['name1', 'name2', 'name3', 'name4'],
['name5', 'name6', 'name7']
]
$('.table').ready(
function() {
console.log('table loaded');
var theTable = "";
for (var j = 0; j < mdArray.length; j++) {
theTable += '<tr class="text-center">';
for (var k = 0; k < 2; k++) {
theTable += '<td> class="text-center"' + mdArray[k][j] + '</td>';
}
theTable += '</tr>';
}
$('.table').append(theTable);
//expected name1 name2 name3 name4
//next row
//name5 name6 name7
});
<script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap#5.1.3/dist/css/bootstrap.min.css" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.1.3/dist/js/bootstrap.min.js" integrity="sha384-QJHtvGhmr9XOIpI6YVutG+2QOK9T+ZnN4kzFN1RtK3zEFEIsxhlmWl5/YESvpZ13" crossorigin="anonymous"></script>
<body>
<table class="table table">
<tbody>
</tbody>
</table>
</body>
Because someone suggested a visual representation:
Is this what you looking for
<html>
<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" />
<title>Document</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap#5.1.3/dist/css/bootstrap.min.css" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous" />
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.1.3/dist/js/bootstrap.min.js" integrity="sha384-QJHtvGhmr9XOIpI6YVutG+2QOK9T+ZnN4kzFN1RtK3zEFEIsxhlmWl5/YESvpZ13" crossorigin="anonymous"></script>
</head>
<body>
<!-- <button onclick="eventEmitArray()">Insert the array</button> -->
<table class="table">
<tbody></tbody>
</table>
</body>
<script>
let mdArray = [
["name1", "name2", "name3", "name4"],
["name5", "name6", "name7"],
];
$(".table").ready(function() {
console.log("table loaded");
var theTable = "";
for (var j = 0; j < mdArray.length; j++) {
theTable += '<tr class="text-center">';
for (var k = 0; k < mdArray[j].length; k++) {
theTable += '<td class="text-center">' + mdArray[j][k] + "</td>";
}
theTable += "</tr>";
}
$(".table").append(theTable);
});
</script>
</html>
You can use forEach loop and you don't need to worry about number of columns and handling array indexes
$('.table').ready(function() {
var theTable = "";
mdArray.forEach((names) => {
theTable += '<tr class="text-center">'
names.forEach((name) => {
theTable += `<td class="text-center">${name}</td>`;
})
theTable += '</tr>'
}
);
$('.table').append(theTable);
});
Related
How to create a fully dynamic table with dynamic rowspan ?
My data will change according to user search and the data shown below is just a sample only.
Sample data and partially dynamic code is below I would like to make it fully dymnamic.
please help me to make it fully dynamic so that I can display the content efficiently.
<html>
<script
src="https://code.jquery.com/jquery-3.6.0.min.js"
integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4="
crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/2.3.2/js/bootstrap.min.js" integrity="sha512-28e47INXBDaAH0F91T8tup57lcH+iIqq9Fefp6/p+6cgF7RKnqIMSmZqZKceq7WWo9upYMBLMYyMsFq7zHGlug==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/2.3.2/css/bootstrap.css" integrity="sha512-Fik9pU5hBUfoYn2t6ApwzFypxHnCXco3i5u+xgHcBw7WFm0LI8umZ4dcZ7XYj9b9AXCQbll9Xre4dpzKh4nvAQ==" crossorigin="anonymous" referrerpolicy="no-referrer" />
<body>
<script>
$(document).ready(function(){
var data = [];
data[0] = ["text1","cat1","121 AA","50"];
data[1] = ["text1","cat1","125 BB","45"];
data[2] = ["text2","cat2","214 CC","27"];
data[3] = ["text3","cat3","245 KP","31"];
data[4] = ["text4","cat4","425 DD","43"];
data[5] = ["text4","cat4","111 CC","95"];
data[6] = ["text5","cat5","222 EE","64"];
data[7] = ["text6","cat6","425 FF","72"];
var htmls= "";
htmls = "<table class='table table-hover table-bordered'>"+
"<tr>"+
"<th>TITE 1</th>"+
"<th>TITE 2</th>"+
"<th>TITE 3</th>"+
"<th>TITE 4</th>"+
"</tr>";
for(var i=0;i<data.length;i++){
if(i==0 || i==1){
var i2 = 1+1;
htmls +="<tr>"+
"<td rowspan='2'>"+data[i][0]+"</td>"+
"<td rowspan='2'>"+data[i][1]+"</td>"+
"<td>"+data[i][2]+"</td>"+
"<td>"+data[i][3]+"</td>"+
"</tr>";
htmls +="<tr>"+
"<td>"+data[i2][2]+"</td>"+
"<td>"+data[i2][3]+"</td>"+
"</tr>";
i=i+1;
}
else if(i==4 || i==5){
htmls +="<tr>"+
"<td rowspan='2'>"+data[i][0]+"</td>"+
"<td rowspan='2'>"+data[i][1]+"</td>"+
"<td>"+data[i][2]+"</td>"+
"<td>"+data[i][3]+"</td>"+
"</tr>";
htmls +="<tr>"+
"<td>"+data[i+1][2]+"</td>"+
"<td>"+data[i+1][3]+"</td>"+
"</tr>";
i=i+1;
}
else{
htmls +="<tr>"+
"<td>"+data[i][0]+"</td>"+
"<td>"+data[i][1]+"</td>"+
"<td>"+data[i][2]+"</td>"+
"<td>"+data[i][3]+"</td>"+
"</tr>";
}
}
$("#htmls").html(htmls);
});
</script>
<div id='htmls'></div>
</body>
</html>
Consider the following.
$(function() {
var data = [];
data[0] = ["text1", "cat1", "121 AA", "50"];
data[1] = ["text1", "cat1", "125 BB", "45"];
data[2] = ["text2", "cat2", "214 CC", "27"];
data[3] = ["text3", "cat3", "245 KP", "31"];
data[4] = ["text4", "cat4", "425 DD", "43"];
data[5] = ["text4", "cat4", "111 CC", "95"];
data[6] = ["text5", "cat5", "222 EE", "64"];
data[7] = ["text6", "cat6", "425 FF", "72"];
function getCatCount(c) {
var results = 0;
$.each(data, function(i, r) {
if (r[1] == c) {
results++;
}
});
return results;
}
var table = $("<table>", {
class: "table table-hover table-bordered"
});
var head = $("<thead>").appendTo(table);
var body = $("<tbody>").appendTo(table);
$("<tr>").appendTo(head);
$("<th>").html("Title 1").appendTo($("tr", head));
$("<th>").html("Title 2").appendTo($("tr", head));
$("<th>").html("Title 3").appendTo($("tr", head));
$("<th>").html("Title 4").appendTo($("tr", head));
var currentCat = "";
$.each(data, function(i, r) {
var row = $("<tr>").appendTo(body);
if (r[1] != currentCat) {
currentCat = r[1];
$.each(r, function(j, c) {
if (j < 2) {
$("<td>", {
rowspan: getCatCount(currentCat)
}).html(c).appendTo(row);
} else {
$("<td>").html(c).appendTo(row);
}
});
} else {
$.each(r, function(j, c) {
if (j >= 2) {
$("<td>").html(c).appendTo(row);
}
});
}
});
$("#htmls").html(table);
});
<script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/2.3.2/js/bootstrap.min.js" integrity="sha512-28e47INXBDaAH0F91T8tup57lcH+iIqq9Fefp6/p+6cgF7RKnqIMSmZqZKceq7WWo9upYMBLMYyMsFq7zHGlug==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/2.3.2/css/bootstrap.css" integrity="sha512-Fik9pU5hBUfoYn2t6ApwzFypxHnCXco3i5u+xgHcBw7WFm0LI8umZ4dcZ7XYj9b9AXCQbll9Xre4dpzKh4nvAQ==" crossorigin="anonymous" referrerpolicy="no-referrer"
/>
<div id='htmls'></div>
This uses more jQuery to build the table. You need a bit more complex logic to build the rowspans. 1. You need to know how many categories there will be for each Category. 2. You need to conditionally build the rows in relationship to each other.
The Logic I used is based on the following example: https://jqueryui.com/autocomplete/#categories
I know there are a lot of similar questions out there. This code is a Frankenstein of a lot of other stack overflow questions. But I am so close I just don't understand the code I've been trying to use an examples very well.
Here is my html page:
<!DOCTYPE html>
<html>
<script src="Scripts.js"></script>
<script>
</script>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8" />
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"> </script>
</head>
<body>
<p id="demo"></p>
<script>
obj.Blades.forEach(element => {
var name = element.Name + " " + element.Damage;
document.write(name + "<br >");
});
</script>
<input type="button" value="Generate Table" onclick="makeTable()" />
<hr />
<div id="dvTable"></div>
</body>
</html>
And here is the Java Script page:
var jsonStuff = '{ "Blades" : [' +
'{ "Name":"Longsword" , "Damage":"l2d" },' +
'{ "Name":"Dagger" , "Damage":"l3d" },' +
'{ "Name":"Mace" , "Damage":"l4d" },' +
'{ "Name":"Spear" , "Damage":"l5d" } ]}';
var obj = JSON.parse(jsonStuff);
function makeTable(){
//Create a HTML Table element.
var table = document.createElement("TABLE");
table.border = "1"
//Get the count of columns.
var columnCount = Object.keys(obj.Blades).length;
//Add the header row.
var row = table.insertRow(-1);
for (var i = 0; i < columnCount; i++) {
var headerCell = document.createElement("TH");
headerCell.innerHTML = obj.Blades[i].Name;
row.appendChild(headerCell);
}
//Add the data rows.
for (var i = 1; i < obj.Blades.length; i++) {
row = table.insertRow(-1);
for (var j = 0; j < columnCount; j++) {
console.log(obj.Blades[j].Damage);
var cell = row.insertCell(-1);
cell.innerHTML = obj.Blades[i][j];
}
}
var dvTable = document.getElementById("dvTable");
dvTable.innerHTML = "";
dvTable.appendChild(table);
}
This is what it looks like right now:
So I know the problem has to be somewhere in the section of JavaScript commented "add the Data rows". I'm just now sure how to go about it.
I believe your problem is with the line:
cell.innerHTML = obj.Blades[i][j];
You are referring to Blades as if it were a 2-dimensional array, when in fact it is an array of objects. You're going to need to have something like this to avoid the undefined:
cell.innerHTML = obj.Blades[i].Name;
cell.innerHTML = obj.Blades[i].Damage;
I try to use bootstrap 3 tooltip in my website, and use html to show the content of tooltip, but I get an error: Cannot read property 'user' of undefined.
<div class="container">
Hover over me
Hover over me
Hover over me
Hover over me
Hover over me
</div>
$(document).ready(function() {
var data = [{'user': "Amy"}, {'user': "Betty"}, {'user': "Cindy"}, {'user': "Debby"}, {'user': "Emily"}];
setTooltip(data);
})
function setTooltip(data) {
for (var i = 0; i < data.length; i++) {
$('[data-idx="' + i + '"]').tooltip({
html: true,
title: function() {
return "<p>User: " + data[i].user + "</p>";
}
});
}
}
This is the result in the console:
Does anybody have this problem? Thank you.
You will have to update your setTooltip function:
function setTooltip(data) {
for (var i = 0; i < data.length; i++) {
const name = data[i].user;
$('[data-idx="' + i + '"]').tooltip({
html: true,
title: "<p>User: " + name + "</p>"
});
}
}
Working fiddle:
https://jsfiddle.net/yqdhkcvz/10/
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<link href="https://code.jquery.com/ui/1.12.1/themes/smoothness/jquery-ui.css" rel="stylesheet" type="text/css" />
<script src="https://code.jquery.com/jquery-3.1.0.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<script src="https://code.jquery.com/jquery.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" type="text/css" />
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<title>Tooltip Test</title>
</head>
<body>
<div class="container">
Hover over me
Hover over me
Hover over me
Hover over me
Hover over me
</div>
</body>
</html>
$(document).ready(function() {
var data = [{'user': "Amy"}, {'user': "Betty"}, {'user': "Cindy"}, {'user': "Debby"}, {'user': "Emily"}];
setTooltip(data);
})
function setTooltip(data) {
for (var i = 0; i < data.length; i++) {
$('[data-idx="' + i + '"]').tooltip({
title: "User: " + data[i].user
});
}
}
Please try the above solution it is working fine.
The issue I found in your code that you were using a function() to set the tooltip and the data[i] was undefined within that scope.
Tested link: https://jsbin.com/viyipewale/edit?html,js
Please try this following:
function setTooltip(data) {
for (var i = 0; i < data.length; i++) {
if($('[data-idx="' + i + '"]').length > 0){//Checking the element exists or not
$('[data-idx="' + i + '"]').tooltip({
title: "User: " + data[i].user
});
}
}
}
It's working fine.
I want to create a dynamic table using html and js. I put the below code and its not working. I can do that in many number of ways. But i want know why this code is not working.
This is my code
let data = [{
id: 1,
name: 'ssss'
},
{
id: 2,
name: 'bbbb'
}
]
document.getElementById("test").innerHTML = `<table><tr><th>S.no</th><th>title</th></tr>`;
data.forEach(item => {
document.getElementById("test").innerHTML += "<tr><td>" + item.id + "</td><td>" + item.name + "</td></tr>";
console.log(item);
});
console.log("ssss");
document.getElementById("test").innerHTML += "</table>";
<p id="test">
</p>
I got the output as below
S.no title
1ssss2bbbb
My expected output is
S.no title
1 ssss
2 bbbb
Put the </table> into the HTML string from the beginning.
test is a <p> element, not a table element. Select the table element instead, which is a direct descendant of the <p>.
If you're confusing yourself, it'll be clearer if you extract the elements into descriptive variable names first, like this:
let data = [{
id: 1,
name: 'ssss'
},
{
id: 2,
name: 'bbbb'
}
]
const p = document.getElementById("test");
p.innerHTML = `<table><tr><th>S.no</th><th>title</th></tr></table>`;
const table = p.children[0];
data.forEach(item => {
table.innerHTML += "<tr><td>" + item.id + "</td><td>" + item.name + "</td></tr>";
});
<p id="test">
</p>
Try to set table after all work done like this:
let data = [{
id: 1,
name: 'ssss'
},
{
id: 2,
name: 'bbbb'
}
]
var x = `<table><tr><th>S.no</th><th>title</th></tr>`;
data.forEach(item => {
x += "<tr><td>" + item.id + "</td><td>" + item.name + "</td></tr>";
});
x += "</table>";
document.getElementById("test").innerHTML = x
console.log(x)
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Page Title</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<p id="test">
</p>
</body>
</html>
Try to set id for <tbody> part of the table and set the innerHTML with js like below:
let data = [{
id: 1,
name: 'ssss'
},
{
id: 2,
name: 'bbbb'
}
]
document.getElementById("test").innerHTML = `<table><tr><th>S.no</th><th>title</th></tr><tbody id="tableBody"></tbody></table>`;
data.forEach(item => {
document.getElementById("tableBody").innerHTML += "<tr><td>" + item.id + "</td><td>" + item.name + "</td></tr>";
console.log(item);
});
console.log("ssss");
document.getElementById("test").innerHTML += "</table>";
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Page Title</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<p id="test" />
</body>
</html>
I have modified your approach a bit:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Page Title</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<p id="test">
</table>
</p>
<script>
let data = [{
id: 1,
name: 'ssss'
},
{
id: 2,
name: 'bbbb'
}
]
var table = document.createElement('table');
var thead = document.createElement('thead');
var tbody = document.createElement('tbody');
var tr = document.createElement('tr');
var td = document.createElement('td');
var columns = ['S.No','Title'];
var tcol = [];
//creating the header while assuming all the headers are present in 1st row
Object.keys(data[0]).forEach(col=>{
tcol.push(col);
});
for(var i=0;i<columns.length;i++)
{
var th = document.createElement('th');
th.innerHTML = columns[i];
tr.appendChild(th);
}
thead.appendChild(tr);
//appending the created headers to the table object
table.appendChild(thead);
//creating the body
data.forEach(item => {
tr = document.createElement('tr');
for (var i = 0; i < tcol.length; i++) {
var td = document.createElement('td');
td.innerHTML = item[tcol[i]];
tr.appendChild(td);
}
//appending the created row to the table body
tbody.appendChild(tr);
});
table.appendChild(tbody);
//finally putting the table's html to your desired div
document.getElementById("test").innerHTML = table.outerHTML;
</script>
</body>
</html>
I have made an assumption that your 1st row will mostly have a columns in it if not try to pass the columns as a seperate entity.
I'm using javascript DataTables to display a csv file on a webpage. Below is my
javascript file:
var CsvToHtmlTable = CsvToHtmlTable || {};
CsvToHtmlTable = {
init: function (options) {
options = options || {};
var csv_path = options.csv_path || "";
var el = options.element || "table-container";
var allow_download = options.allow_download || false;
var csv_options = options.csv_options || {};
var datatables_options = options.datatables_options || {};
var custom_formatting = options.custom_formatting || [];
$("#" + el).html("<table class='table table-striped table-condensed' id='" + el + "-table'></table>");
$.when($.get(csv_path)).then(
function(data){
var csv_data = $.csv.toArrays(data, csv_options);
var table_head = "<thead><tr>";
for (head_id = 0; head_id < csv_data[0].length; head_id++) {
table_head += "<th>" + csv_data[0][head_id] + "</th>";
}
table_head += "</tr></thead>";
$('#' + el + '-table').append(table_head);
$('#' + el + '-table').append("<tbody></tbody>");
for (row_id = 1; row_id < csv_data.length; row_id++) {
var row_html = "<tr>";
var color = "red";
//takes in an array of column index and function pairs
if (custom_formatting != []) {
$.each(custom_formatting, function(i, v){
var col_idx = v[0]
var func = v[1];
csv_data[row_id][col_idx]= func(csv_data[row_id][col_idx]);
})
}
for (col_id = 0; col_id < csv_data[row_id].length; col_id++) {
if (col_id === 2) {
row_html += "<td>" + parseFloat(csv_data[row_id][col_id]) + "</td>";
}
else {
row_html += "<td>" + csv_data[row_id][col_id] + "</td>";
}
if (parseFloat(csv_data[row_id][2]) <= 1 && parseFloat(csv_data[row_id][2]) > 0.7) {
color = "red";
}
else if (parseFloat(csv_data[row_id][2]) <= 0.7 && parseFloat(csv_data[row_id][2]) >= 0.5) {
color = "orange";
}
else {
color = "yellow";
}
}
row_html += "</tr>";
$('#' + el + '-table tbody').append(row_html).css("background-color", color));
}
$('#' + el + '-table').DataTable(datatables_options);
if (allow_download)
$("#" + el).append("<p><a class='btn btn-info' href='" + csv_path + "'><i class='glyphicon glyphicon-download'></i> Download as CSV</a></p>");
});
}
}
And below is my index.html file:
<!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">
<!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags -->
<title>CSV to HTML Table</title>
<!-- Bootstrap core CSS -->
<link href="css/bootstrap.min.css" rel="stylesheet">
<link href="css/dataTables.bootstrap.css" rel="stylesheet">
<!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->
<!--[if lt IE 9]>
<script type="text/javascript" src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
<script type="text/javascript" src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body>
<div class="container-fluid">
<h2>CSV to HTML Table</h2>
<div id='table-container'></div>
</div><!-- /.container -->
<!-- Bootstrap core JavaScript
================================================== -->
<!-- Placed at the end of the document so the pages load faster -->
<script type="text/javascript" src="js/jquery.min.js"></script>
<script type="text/javascript" src="js/bootstrap.min.js"></script>
<script type="text/javascript" src="js/jquery.csv.min.js"></script>
<script type="text/javascript" src="js/jquery.dataTables.min.js"></script>
<script type="text/javascript" src="js/dataTables.bootstrap.js"></script>
<script type="text/javascript" src="js/csv_to_html_table.js"></script>
<script type="text/javascript">
function format_link(link){
if (link)
return "<a href='" + link + "' target='_blank'>" + link + "</a>";
else
return "";
}
CsvToHtmlTable.init({
csv_path: 'data/fatty_acid_profiles.csv',
element: 'table-container',
allow_download: true,
csv_options: {separator: ','},
datatables_options: {"paging": false},
custom_formatting: [[4, format_link]]
});
</script>
</body>
</html>
My webpage currently looks like this:
I want to know is it possible in DataTables that for 2nd & 3rd columns, I get a Filter along with the column name so that we can select for which specific values we want to view data for, something like what we have in Excel (using Sort & Filter)?? Please help!!
Yes, it is possible with a customized solution.
You need to read all columns and add distinct members to dropdowns like this.
$(document).ready(function() {
$('#example').DataTable( {
initComplete: function () {
this.api().columns().every( function () {
var column = this;
var select = $('<select><option value=""></option></select>')
.appendTo($(column.header()).empty())
.on('change', function () {
var val = $.fn.dataTable.util.escapeRegex(
$(this).val()
);
column
.search( val ? '^'+val+'$' : '', true, false )
.draw();
});
column.data().unique().sort().each( function ( d, j ) {
select.append( '<option value="'+d+'">'+d+'</option>' )
});
});
}
});
});
By using column().search() functionality, you will have a column based filter with dropdowns. You can move dropdowns from header to footer by changing .appendTo($(column.header()).empty()) to .appendTo($(column.footer()).empty()).
Examples:
jsFiddle (header dropdowns)
jsFiddle (footer dropdowns)