How to show checkboxes in jquery.datatables? - javascript

I am using Datatables and I have the following code to generate the table. I want to display checkboxes for the read, write, execute and admin values.
If the value is equal to 1 , I want the checkbox to be checked. and if 0 checkboxes unchecked.
Javascript
<script type="text/javascript" charset="utf-8">
$(document).ready(function() {
var oTable = $('#example').dataTable( {
"sScrollY": "500px",
"bPaginate": false,
"bProcessing": true,
"sAjaxSource": "sources/sample.json"
} );
} );
</script>
HTML
<table cellpadding="0" cellspacing="0" border="0" class="display" id="example">
<thead>
<tr>
<th width="20%">Browser</th>
<th width="25%">Read</th>
<th width="25%">Write</th>
<th width="15%">Execute</th>
<th width="15%">Admin</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
JSON
{ "aaData": [
["Trident","0","0","0","1"],
["Trident","0","1","0","0"],
["Trident","0","0","1","1"],
["Trident","0","0","1","1"],
["Trident","0","0","1","1"],
["Trident","0","0","0","0"],
["Gecko","1","1","1","1"],
["Gecko","0","0","0","1"],
["Other browsers","1","0","0","U"]
] }

I was able to get it to work using the datables mrenderer
$(document).ready(function () {
var oTable = $('#example').dataTable({
"aoColumnDefs": [{
"aTargets": [0],
//"mData": "download_link",
"mRender": function (data, type, full) {
if (data == "Gecko") {
return '' + data + ' Download Gecko';
} else {
return '' + data + ' Download';
}
}
}, {
"aTargets": [1],
//"mData": "download_link",
"mRender": function (data, type, full) {
if (data == "1") {
return '<input type=\"checkbox\" checked value="' + data + '">';
} else {
return '<input type=\"checkbox\" value="' + data + '">';
}
}
}, {
"aTargets": [2],
//"mData": "download_link",
"mRender": function (data, type, full) {
if (data == "1") {
return '<input type=\"checkbox\" checked value="' + data + '">';
} else {
return '<input type=\"checkbox\" value="' + data + '">';
}
}
}, {
"aTargets": [3],
//"mData": "download_link",
"mRender": function (data, type, full) {
if (data == "1") {
return '<input type=\"checkbox\" checked value="' + data + '">';
} else {
return '<input type=\"checkbox\" value="' + data + '">';
}
}
}, {
"aTargets": [4],
//"mData": "download_link",
"mRender": function (data, type, full) {
if (data == "1") {
return '<input type=\"checkbox\" checked value="' + data + '">';
} else {
return '<input type=\"checkbox\" value="' + data + '">';
}
}
}],
"bFilter": false,
"sScrollY": "500px",
"bPaginate": false,
"bProcessing": true,
"sAjaxSource": "sources/sample.json"
});
});

Related

datatables return [object HTMLInputElement]

I use ColumnDef to create column in datatables and it return [object HTMLInputElement] in the note texterea but the other was fine
columnDefs: [
{
title: "STT",
targets: 0,
data: null,
render: function (data, type, row, meta) {
return (meta.row + meta.settings._iDisplayStart + 1);
},
},
{
title: "Loại sản phẩm*",
targets: 1,
data: null,
render: function (data, type, row, meta) {
return '<textarea style="width: 300px;" id="productname' + data.id + '" type="text" onchange="ChangeProductName(\'' + data.id + '\',this)" name="' + data.id + '" value="' + data.productname + '">' + data.productname + '</textarea>';
}
},
{
title: "Điều kiện*",
targets: 2,
data: null,
render: function (data, type, row, meta) {
return '<textarea style="width: 300px;" id="condition' + data.id + '" type="text" onchange="ChangeCondition(\'' + data.id + '\',this)" name="' + data.id + '" value="' + data.condition + '">' + data.condition + '</textarea>';
}
},
{
title: "Rebate(%)*",
targets: 3,
data: null,
width: "70",
render: function (data, type, row, meta) {
return '<div><input id="rebate' + data.id + '" type="number" style="width: 70px;" onchange="ChangeRebate(\'' + data.id + '\',this)" name="' + data.id + '" value="' + data.rebate + '"></div>';
}
},
{
title: "Ghi chú",
targets: 4,
data: null,
/*width: "250",*/
render: function (data, type, row, meta) {
return '<textarea id="note' + data.id + '" type="text" onchange="ChangeNote(\'' + data.id + '\',this)" name="' + data.id + '" value="' + data.note + '">' + data.note + '</textarea>';
}
},
{
title: "",
targets: 5,
data: null,
className: "dt-center",
width: "70",
render: function (data, type, row, meta) {
// return ' <i style="cursor: pointer;font-size: 25px;padding-bottom: 30px;" class="fa fa-trash removePG" aria-hidden="true" onclick=removePG(\'' + data.id + '\')></i>';
return '<div class="btn btn-danger removePG" style="cursor: pointer;font-size:25px;" ><i class="fa-solid fa-trash"></i></div>';
}
},
]
Here is the display
Why only the textarea in note have this error
I appreciate every explanation and suggestion about how I should fix this
It's clearly textarea value issue. Looks like data.note is object, but it've got to be a string. Check it twice)

Show an image in a "Jquery Datatable Plugin" cell using "columns.render" callback

I'm trying to display an image in a cell using the suggested answer from this post: Displaying image on Datatable.
However, the first parameter of the callback (data) should receive the string with the url pointing to the image, but it is always undefined.
This is how I initialize the datatable (columnDefs contains the callback I was talking about):
$().ready(function () {
var opt = {
columnDefs: [{
"targets": 2,
"data": 'teamLogo',
"render": function (data, type, row, meta) {
return '<img src="' + data + '" alt="' + data + '"height="16" width="16"/>';
}
}],
info: false,
order: [[0, 'asc']],
paging: false,
responsive: true,
searching: false
};
$('#dataTable').DataTable(opt);
});
After an ajax call, I update data into the table, drawing it back again:
$('#cmbSeasons').change(function () {
var leagueId = parseInt($('#cmbLeagues').val().toString());
var seasonYear = parseInt($('#cmbSeasons').val().toString());
var settings = {
url: '/Standing/Read/Standings',
type: 'GET',
contentType: 'application/json; charset=utf-8',
dataType: "json",
data: { leagueId: leagueId, seasonYear: seasonYear },
success: function (data) {
var t = $('#dataTable').DataTable();
t.clear();
for (var i = 0; i < data.length; i++) {
t.row.add([
data[i].rank,
data[i].teamName,
data[i].teamLogo,
data[i].points,
data[i].allPlayed,
data[i].allWin,
data[i].allDraw,
data[i].allLose,
data[i].allGoalsFor,
data[i].allGoalsAgainst,
data[i].homePlayed,
data[i].homeWin,
data[i].homeDraw,
data[i].homeLose,
data[i].homeGoalsFor,
data[i].homeGoalsAgainst,
data[i].awayPlayed,
data[i].awayWin,
data[i].awayDraw,
data[i].awayLose,
data[i].awayGoalsFor,
data[i].awayGoalsAgainst
]);
}
t.draw();
},
error: function (result) { alert('error ' + result.status + ': ' + result.responseText); }
};
$.ajax(settings);
});
The third column (data[i].teamLogo) contains the correct url I want to use as src for the image (I'm sure about it because I used the developer console to check the correctness of the string).
This is html Markup:
<table id="dataTable" class="text-center">
<thead class="text-capitalize">
<tr>
<th class="all">Rank</th>
<th class="all">Team</th>
<th class="all">Logo</th>
<th class="all">Pts</th>
<th class="all">Pl</th>
<th class="all">W</th>
<th class="all">D</th>
<th class="all">L</th>
<th class="all">GF</th>
<th class="all">GA</th>
<th class="all">HPl</th>
<th class="all">HW</th>
<th class="all">HD</th>
<th class="all">HL</th>
<th class="all">HGF</th>
<th class="all">HGA</th>
<th class="all">APl</th>
<th class="all">AW</th>
<th class="all">AD</th>
<th class="all">AL</th>
<th class="all">AGF</th>
<th class="all">AGA</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
Is there anything wrong with the callback I wrote? Should be "data" parameter populated with a different string, instead of 'teamLogo'?
I'm using the latest version of datatables (1.10.20) and Jquery (3.5.1).
return '<img src="' + data + '" alt="' + data + '"height="16" width="16"/>';
use an Img object to return instead
https://www.w3schools.com/jsref/dom_obj_image.asp
Changing the definition of the options this way:
$().ready(function () {
let opt: DataTables.Settings = {
columns: [
{ "data": "rank" },
{ "data": "teamName" },
{ "data": "teamLogo" },
{ "data": "points" },
{ "data": "allPlayed" },
{ "data": "allWin" },
{ "data": "allDraw" },
{ "data": "allLose" },
{ "data": "allGoalsFor" },
{ "data": "allGoalsAgainst" },
{ "data": "homePlayed" },
{ "data": "homeWin" },
{ "data": "homeDraw" },
{ "data": "homeLose" },
{ "data": "homeGoalsFor" },
{ "data": "homeGoalsAgainst" },
{ "data": "awayPlayed" },
{ "data": "awayWin" },
{ "data": "awayDraw" },
{ "data": "awayLose" },
{ "data": "awayGoalsFor" },
{ "data": "awayGoalsAgainst" }
],
columnDefs:
[{
"targets": 2,
"data": 'teamLogo',
"render": function (data, type, row, meta) {
return '<img src="' + data + '" alt="' + data + '"height="16" width="16"/>';
}
}],
info: false,
order: [[0, 'asc']],
paging: false,
responsive: true,
searching: false
}
$('#dataTable').DataTable(opt);
});
and simplifying the for loop like this:
t.rows.add( data ).draw();
did the trick!
It seemes that I had to define the data columns for the callback to work properly.

ASPNETZERO - How to change index page to render tiles instead of table

I currently have a normal ASPNETZERO index page, which renders a datatable grid with search fuctions. I want to change this view to render "tiles" for each row in the grid. I already have the CSS/HTML for rendering tiles working. I basically want to repurpose the below index.js code to render my tiles, instead of the datatable grid.
(function () {
$(function () {
var _$companyTable = $('#companyTable');
var _companyService = abp.services.app.company;
var _permissions = {
create: abp.auth.hasPermission('Pages.Tenant.Administration.Company.Create'),
edit: abp.auth.hasPermission('Pages.Tenant.Administration.Company.Edit'),
impersonation: abp.auth.hasPermission('Pages.Tenants.Impersonation'),
};
var _createModal = new app.ModalManager({
viewUrl: abp.appPath + 'Nursing/Company/CreateModal',
scriptUrl: abp.appPath + 'view-resources/Areas/Nursing/Views/Company/_CreateModal.js',
modalClass: 'CreateCompanyModal'
});
var _editModal = new app.ModalManager({
viewUrl: abp.appPath + 'Nursing/Company/EditModal',
scriptUrl: abp.appPath + 'view-resources/Areas/Nursing/Views/Company/_EditModal.js',
modalClass: 'EditCompanyModal'
});
var dataTable = _$companyTable.DataTable({
paging: true,
serverSide: true,
processing: true,
responsive: true,
listAction: {
ajaxFunction: _companyService.getCompanies,
inputFilter: function () {
return {
filter: $('#CompanyTableFilter').val()
};
}
},
columnDefs: [
{
targets: 0,
data: null,
orderable: false,
autoWidth: true,
defaultContent: '',
rowAction: {
cssClass: 'btn btn-xs btn-primary blue',
text: '<i class="fa fa-cog"></i> ' + app.localize('Actions') + ' <span class="caret"></span>',
items: [{
text: app.localize('Edit'),
visible: function () {
return _permissions.edit;
},
action: function (data) {
_editModal.open({ id: data.record.id });
}
}]
}
},
{
targets: 1,
orderable: true,
autoWidth: true,
data: "companyName"
},
{
targets: 2,
orderable: true,
autoWidth: true,
data: "companyLegalName"
},
{
targets: 3,
autoWidth: true,
data: "companyTaxID"
},
{
targets: 4,
orderable: true,
autoWidth: true,
data: "currency"
}
]
});
function getCompanies() {
dataTable.ajax.reload();
}
$('#CreateNewCompanyButton').click(function (e) {
_createModal.open();
});
$('#GetCompaniesButton').click(function (e) {
e.preventDefault();
getCompanies();
});
abp.event.on('app.editCompanyModalSaved', function () {
getCompanies(true);
});
abp.event.on('app.createCompanyModalSaved', function () {
getCompanies(true);
});
$('#CompanyTableFilter').focus();
});
How can I change the JS code above to render my tiles instead of the datatable? I also want to retain the search function for the tiles. The app service method GetCompanies used in the JS code above works for rendering my tiles. So that API call will remain the same.
Here is the output I want to achieve from the above JS code.
Here is the current standard ABP index page view. I want to replace this with above tiles.
I figured out a solution. I changed the index.js code by adding the method shown below. I'm using an AJAX call to the API method and then using the results to render my tiled output. This is working for me.
If anyone sees any issues with this approach, please do let me know.
function getCompanies() {
$.ajax({
type: 'GET',
url: '/api/services/app/Company/GetCompanies',
dataType: 'json',
success: function (companies) {
var _tileHtml = "";
//Iterate thru JSON list of values
$.each(companies.result.items, function (i, company) {
//Tile content start
_tileHtml = "<div class='SingleTileContent inline-block'>";
//Header
_tileHtml += "<div class='Tile-header'>";
_tileHtml += "<div class='pull-left inline-block'>";
_tileHtml += "<div class='badge badge-info'>" + company.id + "</div>";
_tileHtml += "</div>";
_tileHtml += "<div class='pull-left inline-block text-bold'> | " + company.companyName + "</div>";
_tileHtml += "</div>";
//Body start
_tileHtml += "<div class='Tile-body text-left'>";
//Body row
_tileHtml += "<div class='Tile-body-detail'>";
_tileHtml += "<label>Legal Name</label> " + company.companyLegalName + "</div>";
//Body row
_tileHtml += "<div class='Tile-body-detail'>";
_tileHtml += "<label>Tax Id</label> " + company.companyTaxID + "</div>";
//Body end
_tileHtml += "</div>";
//Buttons (footer)
_tileHtml += "<div class='Tile-buttons'>";
_tileHtml += "<a href='javascript:;' class='btn btn-xs blue btnEdit' id='EditCompanyButton'>Edit<i class='fa fa-edit'></i></a>";
_tileHtml += "</div>";
//Tile content end
_tileHtml += "</div>";
$("#TestJS2").append(_tileHtml);
});
Count = 0;
},
error: function (ex) {
abp.notify.error('Failed to retrieve companies' + ex);
}
});
}

Copy Row Table into 'New Table'. | jQuery

I have created a dataTable copy row.
mainTable can only copy to the secondTable.
The problem is when adding New Table,
&
i want the mainTable row can copy into New Table.
i already create "Create New Table" button
New table will append into parent div allTable
MY JSFiddle.
Reference :
I want copy row into selected table(secondTable/newTable). not multiple. and I dont know how to add the selected button, because I'm using a variable.
I have parent div class="allTable" for Table/children (mainTable,
secondTable, and New Table).
i have "COPY ROW" for copy row table from mainTable to another Table, but now only work to copy into the secondTable.
In the $(document).ready(function()),
I have created dataTable for mainTable and secondTable.
mainTable ID is #table1
secondTable ID is #table2
New Table ID is #newTable + index (newTable(3) )
New Table will display blank data.
SCREENSHOT :
I really hope for your help.
This works, but you can improve it, I hope you can get the idea from here, this is not fully working as intended but the flow might help you.
https://jsfiddle.net/o6ysgzps/26/ I have updated the fiddle,
as you can see, I collected the list of tables that are created, and looped to each tables with a confirmation box to select which table you want it to be copied to., You can use bootstrap modal and jquery confirm to make it better,
You can make it cleaner,
html
<body>
<select id='cboList' style=''></select>
<div class="allTable">
<div class="one" style="padding-bottom:50px">
<h2>TABLE 1</h2>
<table id="table1" class="table table-bordered table-hover">
<thead>
<tr>
<th></th>
<th>Audience Name</th>
<th>Type</th>
<th>Size</th>
<th>Date Created</th>
</tr>
</thead>
</table>
</div>
<br>
<button id="Copy">COPY ROW »</button>
<!-- <button id="LeftMove" style="float:left;">« left</button> -->
<br>
<h2>TABLE 2</h2>
<div class="two">
<table id="table2" class="table table-bordered table-hover">
<thead>
<tr>
<th></th>
<th>Audience Name</th>
<th>Type</th>
<th>Size</th>
<th>Date Created</th>
</tr>
</thead>
</table>
</div>
<br>
<br>
<br>
<input type="button" class="submitButton" value="Create New Table">
<h2>NEW TABLE GOES HERE</h2>
</div>
</body>
This is the js
$(document).ready(function() {
var mainTable = $('#table1').dataTable({
"ajax": "https://api.myjson.com/bins/zvujb",
"columns": [{
"data": "id"
}, {
"data": "name"
}, {
"data": "subtype"
}, {
"data": "approximate_count"
}, {
"data": "time_created"
}],
"columnDefs": [{
"targets": 0,
"checkboxes": {
"selectRow": true
},
"render": function(data, type, full, meta) {
return '<input type="checkbox" name="id[]" value="' + $('<div/>').text(data).html() + '">';
}
}],
"scrollY": "200px",
}); // mainTable
var secondTable = $('#table2').dataTable({
"columns": [{
"data": "id"
}, {
"data": "name"
}, {
"data": "subtype"
}, {
"data": "approximate_count"
}, {
"data": "time_created"
}],
"columnDefs": [{
"targets": 0,
"checkboxes": {
"selectRow": true
},
"render": function(data, type, full, meta) {
return '<input type="checkbox" name="id[]" value="' + $('<div/>').text(data).html() + '">';
}
}],
"scrollY": "200px",
"scrollCollapse": "true"
}); // secondTable
mainTable.on('click', 'tbody tr', function() {
$(this).toggleClass('selected');
});
$('#Copy').on('click', function() {
var tables = $(".allTable").find("table*[id]").not("#table1");
tables.each(function(){
console.log(this.id);
var tbl_id = this.id;
var $elem = $(this);
var r = confirm("Copy to table "+tbl_id+"?");
var table_to_copy = $elem.dataTable();
if (r == true) {
copyRows(mainTable, table_to_copy);
alert("Copied!");
} else {
}
});
//
});
}); // end of $(document).ready...
function copyRows(fromTable, toTable) {
var $row = fromTable.find(".selected");
$.each($row, function(k, v) {
if (this !== null) {
addRow = fromTable.fnGetData(this);
toTable.fnAddData(addRow); // <-- Copy Row
// fromTable.fnDeleteRow(this); <-- Move row, delete main row.
}
});
}
var tableIndex = 3;
$('.submitButton').click(function() {
let addIndex = tableIndex++;
var addTable = '<div class="newTable'+ addIndex +'">' +
'<table id="newTable'+ addIndex +'" class="table table-bordered table-hover">' +
'<thead>' +
'<tr>' +
'<th></th>' +
'<th>Audience Name</th>' +
'<th>Type</th>' +
'<th>Size</th>' +
'<th>Date Created</th>' +
'</tr>' +
'</thead>' +
'</table>' +
'</div>';
$('.allTable').append(addTable);
var newTable = $("#newTable"+ addIndex).dataTable({
"columns": [{
"data": "id"
}, {
"data": "name"
}, {
"data": "subtype"
}, {
"data": "approximate_count"
}, {
"data": "time_created"
}],
"columnDefs": [{
"targets": 0,
"checkboxes": {
"selectRow": true
},
"render": function(data, type, full, meta) {
return '<input type="checkbox" name="id[]" value="' + $('<div/>').text(data).html() + '">';
}
}],
"scrollY": "200px",
"scrollCollapse": "true"
}); // newTable
});
modify your code as follow:
function copyRows(fromTable, toTable) {
var toTable = $("table:last").dataTable(); // add this line to the function. Then you can remove toTable from parameters

DataTables mRender function with view model

I'm implement table as http://www.datatables.net/examples/api/form.html, but in javascript I can't data-bind values from my viewmodel("vm") in "mRender". With test render function work correctly. How implement binding with viewmodel in javascript code?
function CreateNewDllTable(url, vm) {
var oTable = $('#test-table').dataTable({
"bProcessing": true,
"bServerSide": true,
"bPaginate": false,
"scrollY": "250px",
"bSort": false,
"bFilter": false,
"bInfo": false,
"sAjaxDataProp": "dataValues",
"sAjaxSource": url
},
"bAutoWidth": false,
"aoColumns": [
{ "mData": "name" },
{
type: 'text',
"mData": "description",
"mRender": function (data) {
if (data == true) {
return '<input type="text"/>';
} else {
return '<input type="text"/>';
}
}
},
{
"mRender": function (data) {
return "<select class='multiselect'>"
+ "<option>Value1</option>"
+ "<option>Value2</option>"
+ "<option>Value3</option>"
+ "<option>Value4</option>"
+ "<option>Value5</option>"
+ "</select>";
}
}
],
"fnDrawCallback": function () {
$("select.multiselect").multiselect();
},
}
For example binding in html:
<select class="multiselect" data-bind="
options: vm.types,
value: vm.selectedTypeId,
optionsText:'type',
optionsValue: 'typeId'">
</select>
For example you can used this code:
"mRender": function () {
var returnValue = "<select class='multiselect'>";
var types = vm.types;
var listItems = "";
for (var i = 0; i < types.length; i++) {
listItems += "<option value='" + types[i].typeId + "'" + " selected='selected'" + ">" + types[i].type + "</option>";
}
return returnValue.concat(listItems, "</select>");
}

Categories

Resources