DataTables mRender function with view model - javascript

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>");
}

Related

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);
}
});
}

Datatables dynamically change on row but data object not change ajax

we coding a quotation form for our company and want to add products a datatable and changing value on it. After change data we send to controller but they same the first time. Here is datatable structure.
var selectedProduct = $('#selectedproduct').DataTable({
"columns": [
{
"orderable": false,
"data": "IsConfirm",
},
{ "orderable": false, "data": "Product.Id" },
{ "orderable": false, "data": "Product.Name" },
{ "orderable": false, "data": "Product.Description" },
{
"orderable": false,
"data": "Quantity",
"render": function (data, type, full, meta) {
return '<td width="100px"><input class="touchspinquantity" type="text" value="' + data + '" name="quantity"></td>';
}
},
{ "orderable": false, "data": "Product.SalePrice" },
{
"orderable": false,
"data": "Discount",
"render": function (data, type, full, meta) {
return '<td width="100px"><input class="touchspindiscount" type="text" value="' + data + '" name="discount"></td>';
}
},
{ "orderable": false, "data": "Product.Currency" },
{ "orderable": false, "data": null, "defaultContent": '' },
{
"orderable": false,
"data": null,
"defaultContent": '<button id="deleteproduct" class="btn btn-warning btn-circle" type="button"><i class="fa fa-times"></i></button>'
},
],
"createdRow": function (row, data, index) {
if (data.IsConfirm) {
$('td', row).eq(0).html('<input type="checkbox" checked class="i-checks" name="input[]">');
}
else {
$('td', row).eq(0).html('<input type="checkbox" class="i-checks" name="input[]">');
}
},
"searching": false,
"paging": false,
"bInfo": false,
"ordering": false
});
Here is how to get data
var datat = table.fnGetData();
You may need to redraw the datatable after the updation
selectedProduct.draw();
I solved problem but maybe that's not good way.
Here is the solve
var rows = table.fnGetNodes();
var arr = [[]];
for (var i = 0; i < rows.length; i++) {
var detaildata = [];
var cells = rows[i].cells;
detaildata[0] = cells[0].childNodes["0"].checked;
detaildata[1] = cells[1].innerText;
detaildata[2] = cells[2].innerText;
detaildata[3] = cells[3].innerText;
detaildata[4] = cells[4].firstChild.childNodes[1].value;
detaildata[5] = cells[5].innerText;
detaildata[6] = cells[6].firstChild.childNodes[1].value;
detaildata[7] = cells[7].innerText;
detaildata[8] = cells[8].innerText;
arr[[i]] = detaildata;
//var select = cells[0].children[0].value;
//if (cells[0].children[0].checked) {
// select = cells[0].children[0].value;
//} else {
// select = 'off';
//}
}

Event only fires once when making Ajax request in jQuery

I have a couple of drop downs that are populated from SharePoint using SPServices. This part works great. But then, I have a button that on click loads data from SharePoint and uses the dropdown texts as filter to fetch the data that will populate a table using the DataTables plugin. This part works only once; if I click the button again, nothing happens.
This is how I populate the dropdowns:
$(document).ready(function () {
var theYear; // Selected Year
var theRO; // Selected RO
//Fills the Dropdown lists (Year and RO)
$().SPServices({
operation: "GetListItems",
async: false,
listName: "{ListID}",
CAMLViewFields: "<ViewFields><FieldRef Name='Fiscal_x0020_Year' /><FieldRef Name='Regional_x0020_Office' /></ViewFields>",
completefunc: function (xData, Status) {
//Add Select Value option
$("#dropdown").prepend($('<option>', {
value: '',
text: 'Select Fiscal Year'
}));
$("#dropdownRO").prepend($('<option>', {
value: '',
text: 'Select Regional Office'
}));
//Fetching Data from SharePoint
$(xData.responseXML).SPFilterNode("z:row").each(function () {
var dropDown = "<option value='" + $(this).attr("ows_Fiscal_x0020_Year") + "'>" + $(this).attr("ows_Fiscal_x0020_Year") + "</option>";
var dropDownRO = "<option value='" + $(this).attr("ows_Regional_x0020_Office") + "'>" + $(this).attr("ows_Regional_x0020_Office") + "</option>";
$("#dropdown").append(dropDown);
$("#dropdownRO").append(dropDownRO);
/////////////Deletes duplicates from dropdown list////////////////
var usedNames = {};
$("#dropdown > option, #dropdownRO > option").each(function () {
if (usedNames[this.text]) {
$(this).remove();
} else {
usedNames[this.text] = this.value;
}
});
////Deletes repeated rows from table
var seen = {};
$('#myTable tr, #tasksUL li, .dropdown-menu li').each(function () {
var txt = $(this).text();
if (seen[txt]) $(this).remove();
else seen[txt] = true;
});
});
} //end of completeFunc
}); //end of SPServices
$('.myButton').on('click', function () {
run()
});
}); //End jQuery Function
This is the function I need to run every time I click on "myButton" after changing my selection in the dropdowns:
function run() {
theYear = $('#dropdown option:selected').text(); // Selected Year
theRO = $('#dropdownRO option:selected').text(); // Selected RO
var call = $.ajax({
url: "https://blah-blah-blah/_api/web/lists/getByTitle('Consolidated%20LC%20Report')/items()?$filter=Fiscal_x0020_Year%20eq%20'" + theYear + "' and Regional_x0020_Office eq '" + theRO + "'&$orderby=Id&$select=Id,Title,Fiscal_x0020_Year,Notices_x0020_Received,Declined_x0020_Participation,Selected_x0020_Field_x0020_Revie,Selected_x0020_File_x0020_Review,Pending,Pending_x0020_Previous_x0020_Yea,Controversial,GFP_x0020_Reviews,NAD_x0020_Appeals,Mediation_x0020_Cases,Monthly_x0020_Cost_x0020_Savings,Monthly_x0020_Expenditure,Regional_x0020_Office,Month_Number", //Works, filters added
type: "GET",
cache: false,
dataType: "json",
headers: {
Accept: "application/json;odata=verbose",
}
}); //End of ajax function///
call.done(function (data, textStatus, jqXHR) {
var oTable = $('#example').dataTable({
"aLengthMenu": [
[25, 50, 100, 200, -1],
[25, 50, 100, 200, "All"]
],
"iDisplayLength": -1, //Number of rows by default. -1 means All Records
"sPaginationType": "full_numbers",
"aaData": data.d.results,
"bJQueryUI": false,
"bProcessing": true,
"aoColumns": [{
"mData": "Id",
"bVisible": false
}, //Invisible column
{
"mData": "Title"
}, {
"mData": "Notices_x0020_Received"
}, {
"mData": "Declined_x0020_Participation"
}, {
"mData": "Selected_x0020_Field_x0020_Revie"
}, {
"mData": "Selected_x0020_File_x0020_Review"
}, {
"mData": "Pending"
}, {
"mData": "Pending_x0020_Previous_x0020_Yea"
}, {
"mData": "Controversial"
}, {
"mData": "GFP_x0020_Reviews"
}, {
"mData": "NAD_x0020_Appeals"
}, {
"mData": "Mediation_x0020_Cases"
}, {
"mData": "Monthly_x0020_Cost_x0020_Savings",
"fnRender": function (obj, val) {
return accounting.formatMoney(val);
}
}, {
"mData": "Monthly_x0020_Expenditure",
"fnRender": function (obj, val) {
return accounting.formatMoney(val);
}
}],
"bDeferRender": true,
"bRetrieve": true,
"bInfo": true,
"bAutoWidth": true,
"bDestroy": true,
"sDom": 'T&;"clear"&;frtip',
"oTableTools": {
"aButtons": ["xls"],
"sSwfPath": "../../Style Library/js/datatables/TableTools/media/swf/copy_csv_xls_pdf.swf",
},
"sSearch": "Filter",
"fnDrawCallback": function () {
//Add totals row
var Columns = $("#example > tbody").find("> tr:first > td").length;
$('#example tr:last').after('<tr><td class="total"></td><td class="total"></td><td class="total"></td><td class="total"></td><td class="total"></td><td class="total"></td><td class="total"></td><td class="total"></td><td class="total"></td><td class="total"></td><td class="total"></td><td class="total"></td><td class="total"></td><td class="total"></td></tr>');
//Formating the Total row number to no decimals
$("#example tr:last td:not(:first,:last)").text(function (i) {
var t = 0;
$(this).parent().prevAll().find("td:nth-child(" + (i + 2) + ")").each(function () {
t += parseFloat($(this).text().replace(/[\$,]/g, '') * 1);
});
return parseInt(t * 100, 10) / 100;
});
//Format the monthly expenditure and savings to currency formatFormating the currency
var cell = new Array();
cell[0] = $('#example tr:last td:nth-child(12)').text();
cell[1] = $('#example tr:last td:nth-child(13)').text();
$('#example tr:last').find('td:nth-child(12)').html(accounting.formatMoney(cell[0]));
$('#example tr:last').find('td:nth-child(13)').html(accounting.formatMoney(cell[1]));
$('#example tr:last').find('td:last').hide();
} //hides extra td that was showing
}); //End of Datatable()
}); //End of call.done function
$('#theTableDiv').slideDown();
} //end of run() function
I'm not a programmer, I'm just trying to learn. I would appreciate any help. Thanks in advance
I would guess that you are replacing the part of the page where the button lives. (you really need to format your code more neatly for SO... use JSFiddle.net and their TidyUp button).
If that is the case you need to use a delegated event handler:
$(document).on('click', '.myButton', function () {
run()
});
This listens at a static ancestor of the desired node, then runs the selector when the event occurs, then it applies the function to any matching elements that caused the event.
document is the fallback parent if you don't have a convenient ancestor. Do not use 'body' for delegated events as it has odd behaviour.

How to show checkboxes in jquery.datatables?

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"
});
});

create empty rows in the data tables

i want to create a table in the datatables which does not have data in the last rows data. i wanna leave it empty with borders. right now i when i 10 rows of data 4on each page. the data get into 3pages where first and second page have 4 rows and when we reach the third page there is only two data and the other space is left blank. i wanna create a table and then fetch data but the datatable is creating the table in my code so. cud anyone suggest how can i leave the last two rows blank and visible.
var dataSet = [];
for(var i = 0; i < data.response.docs.length; i++)
{
var d = data.response.docs[i];
var minPrice = d.min_price;
var minPrice = d.shipping;
var seller_rating = d.rating;
var product_rating = d.product_rating;
var total = minPrice + shipping;
var ships_on = 'n/a';
var delivered_by = 'n/a';
dataSet.push([{ 'url': d.url},
total,
minPrice + '+' + shipping,
ships_on, delivered_by,
seller_rating, product_rating]);
}
$('#data_table').dataTable( {
"aaData": dataSet,
"aaSorting": [[0,'asc'],[0,'desc'],[2,'asc'],[2,'desc'],[3,'asc'],[3,'desc'],[4,'asc'],[4,'desc'],[5,'asc'],[5,'desc'],[6,'asc'],[6,'desc'],[7,'asc'],[7,'desc']],
"iDisplayLength": 4,
"bInfo": true,
"bLengthChange": false,
"bJQueryUI": true,
"bPaginate": true,
"bAutoWidth": false,
"sPaginationType": "full_numbers",
"bAutoWidth": true,
"aoColumns": [
{ "sTitle": "Seller",
"sWidth": "155px",
"sClass": "grey" ,
"fnRender": function(obj) {
var data = obj.aData[ obj.iDataColumn ];
return "<A href='"+ data.url +"'>"+ data.title +"</A>";
}
},//, "sWidth": "130px"
{"sTitle": "Item Matched","sWidth": "100px","sClass":"center yellow","bSortable": false,
"fnRender": function (obj) {
//var img = obj.aData[obj.iDataColumn];
var data = obj.aData[obj.iDataColumn];
return "<img width='90px' height='50px' src='" + data.image + "'/><br>"+ data.name.slice(0,25);
}
},
{ "sTitle": "Total Price(in $)","sClass": "center grey" },
{ "sTitle": "Price + Shipping(in $)","sClass": "center yellow" },
{ "sTitle": "Ships On", "sClass": "center grey" },
{ "sTitle": "Delivered By","sClass": "center yellow" },
{
"sTitle": "Seller rating",
"sClass": "center grey",
"fnRender": function(obj) {
var sReturn = obj.aData[ obj.iDataColumn ];
var val = obj.aData[ obj.iDataColumn ];
if ( sReturn != "N/A") {
$('#fixed').raty({
readOnly: true,
start: val
});
sReturn = $('#fixed').html();
$('#fixed').html("");
}
return sReturn;
}
},
});
I just want the last two rows to be visible wheater they have data or not
if(dataSet != '' || no/4 != 0)
{
//alert(no);
var minPrice = 0;
var shipping = 0;
var seller_rating = 0;
var product_rating = 0;
var ships_on = 'n/a';
var delivered_by = 'n/a';
var total = minPrice + shipping;
var a = no%4;
for(var i=0;i<(4-a);i++)
{
dataSet.push([{'title': '', 'url': ''},
{'image': '', 'name': ''},
'0',
'0',
'n/a', 'n/a',
'0', '0']);
}
}
$('#data_table').dataTable( {
"aaData": dataSet ,
"bSort":true,
"aaSorting": [[0,'desc'],[0,'asc'],[2,'asc'],[2,'desc'],[3,'asc'],[3,'desc'],[4,'asc'],[4,'desc'],[5,'asc'],[5,'desc'],[6,'asc'],[6,'desc'],[7,'asc'],[7,'desc']],
"iDisplayLength": 4,
"bInfo": true,
"bLengthChange": false,
"bJQueryUI": true,
"bPaginate": true,
"bAutoWidth": false,
"sPaginationType": "full_numbers",
"bAutoWidth": true,
"aoColumns": [
{ "sTitle": "Seller",
"sWidth": "155px",
"sClass": "grey" ,
"fnRender": function(obj) {
var data = obj.aData[ obj.iDataColumn ];
return "<a href='"+ data.url +"'>"+ data.title +"</a>";
}
}
Its creating two rows which is not having data and is empty. and will create two empty row. I needed data where in each page thereare 4 data in each page. so i m using it in mutiples of 4.
I don't know about the datatable plugin you have been using however you can pad your dataset with empty values to make it work:
var dataset = ['1','2','3','4','5','6','7','8','9'];
var rowCount = 4;
var mod = dataset.length%rowCount;
if(mod) {
for(var i=mod; i<rowCount;i++) {
dataset.push('')
}
}
http://jsfiddle.net/bsrykt/JJtNN/

Categories

Resources