I am having trouble adding in a delete confirmation on my JQuery datatable. I have a on click method on my delete button which calls the confirmation script which works but, if I click cancel, the row gets deleted when it should only be deleted if "Ok" is clicked.
<script type="text/javascript">
var assetListVM;
$(function () {
assetListVM = {
dt: null,
init: function () {
dt = $('#file_list').DataTable({
"serverSide": true,
"processing": true,
"ajax": {
"url": "#Url.Action("GetFiles","AttachmentsUser")",
"data": function (d) {
d.s = $('input[type=search]').val();
}
},
"columns": [
{ "title": "FileName", "data": "file_name", "searchable": true },
{
"title": "Actions",
"data": "file_name",
"searchable": false,
"sortable": false,
"render": function (data, type, full, meta) {
return 'Download | Delete';
}
}
],
});
},
refresh: function () {
dt.ajax.reload();
}
}
$('body').on('keyup', 'input[type=search]', function () {
assetListVM.refresh();
});
// initialize the datatables
assetListVM.init();
});
</script>
<script>
function DeleteFunction() {
if (confirm('Are you sure you want to delete this user - have you removed all roles for this user?'))
return true;
else {
return false;
}
}
</script>
use return to cancel default browser behavior.
onclick="return DeleteFunction()"
Related
here is i have a datatable based table i have fetched a data from database and displayed using datatable but in this datatable i went to redirect to show for each row of datatable so how to add a route for show with parameter 1d for each row thanks and waiting a positive response!
here is my code
<script>
$(function() {
$("#start_date").datepicker({
"dateFormat": "yy-mm-dd"
});
$("#end_date").datepicker({
"dateFormat": "yy-mm-dd"
});
});
// Fetch records
function fetch(start_date, end_date,zone_id,status_id,sector_id) {
$.ajax({
url: "{{ route('ProjectFilterdate/records') }}",
type: "GEt",
data: {
start_date: start_date,
end_date: end_date,
zone_id:zone_id,
status_id:status_id,
sector_id:sector_id
},
dataType: "json",
success: function(data) {
// Datatables
var i = 1;
$('#records').DataTable({
"data": data.ptojects,
// buttons
"dom": "<'row'<'col-sm-12 col-md-4'l><'col-sm-12 col-md-4'B><'col-sm-12 col-md-4'f>>" +
"<'row'<'col-sm-12'tr>>" +
"<'row'<'col-sm-12 col-md-5'i><'col-sm-12 col-md-7'p>>",
"buttons": [
'copy','excel', 'pdf', 'print'
],
// responsive
"responsive": true,
"columns": [{
"data": "id",
"render": function(data, type, row, meta) {
return i++;
}
},
{
"data": "code"
},
{
"data": "name"
},
{
"data": "proposal_date"
},
{
"data": "proposal_value"
},
{
"data": "contractor"
},
{
"data": "subcontractor"
},
{
render: function ( data, type, row) {
return 'test';
}
},
]
});
}
});
}
i am trying to make an a href route but i don't know how to add an id parameter
here is the link i am trying
{
render: function ( data, type, row) {
return 'test';
}
the place of 1 must be replaced by id for each row
This is how i did t :
return DataTables::of($data)->addIndexColumn()
->addColumn('project', function ($test) {
return $test->project->title;
})
->addColumn('action', function ($test) {
$result = $test->active ? 'btn-success' : 'btn-danger';
return '<a href="' . route('projectDetail', [
'id' => $test->id
]) . '">detail </a>
';
})
->rawColumns([
'action'
])
->make(true);
}
I am using Jquery datatables to export my file into excel from sql database. I have 3 column filtrers on my datatables which are working fine independently. I want them to work with or condition in a way that it gets all the data from the datatable where any one the conditions in the filters is met. below is my sample of code.
$(document).ready(function () {
var table = $('#studentTable').DataTable({
"ajax": {
"url": "/StructuredImportTgts/GetData",
"type": "GET",
"datatype": "json"
},
responsive: 'true',
dom: 'Bfrtip',
buttons: [
'copy', 'excel', 'pdf'
],
"columns": [
{ "data": "PART_NO" },
{ "data": "LEVEL" },
{ "data": "PART_NO" },
{ "data": "PART_NAME" },
{ "data": "L1QTY" },
{ "data": "PL1" },
{ "data": "PL2" },
{ "data": "PL3" },
{ "data": "SupplierLocID" },
{ "data": "SupplierLocID" },
{ "data": "Discrepancies" },
{ "data": "Comments" }
],
initComplete: function () { // After DataTable initialized
this.api().columns([1, 5, 6]).every(function () {
/* use of [1,2,3] for second, third and fourth column. Leave blank - columns() - for all.
Multiples? Use columns[0,1]) for first and second, e.g. */
var column = this;
var select = $('<select><option value=""/></select>')
.appendTo($(column.footer()).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>')
});
}); // this.api function
} //initComplete function
});
});
For someone who is stuck in the similar problem, here is how I tackle it.
$(document).ready(function () {
$('#studentTable').DataTable({
"ajax": {
"url": "/StructuredImportTgts/GetData1",
"type": "GET",
"datatype": "json"
},
dom: 'Bfrtip',
buttons: [
'copy', 'excel', 'pdf'
],
"columns": [
//{ "data": "PART_NO" },
{ "data": "LEVEL" },
{ "data": "PART_NO" },
{ "data": "PART_NAME" },
{ "data": "L1QTY" },
{ "data": "PL1" },
{ "data": "PL2" },
{ "data": "PL3" },
{ "data": "SupplierLocID" },
//{ "data": "SupplierLocID" },
{ "data": "Discrepancies" },
{ "data": "Comments" }
],
initComplete: function () {
this.api().columns([4,5,6]).every(function () {
var column = this;
var select = $('<select><option value=""></option></select>')
.appendTo($(column.footer()).empty())
.on('change', function () {
$('#studentTable').DataTable().draw();
});
column.data().unique().sort().each(function (d, j) {
select.append('<option value="' + d + '">' + d + '</option>')
});
});
}
});
});
$.fn.dataTable.ext.search.push(
function (settings, searchData, index, rowData, counter) {
if (settings.nTable.id !== 'studentTable') {
return true;
}
var position = $("#position option:selected").text();
var office = $("#office option:selected").text();
var off = $("#off option:selected").text();
// Display the row if both inputs are empty
if (position.length === 0 && office.length === 0 && off.length === 0) {
return true;
}
// Display row if position matches position selection
hasPosition = true;
if (position !== searchData[4]) {
hasPosition = false; //Doesn't match - don't display
}
// Display the row if office matches the office selection
hasOffice = true;
if (office !== searchData[5]) {
hasOffice = false; //Doesn't match - don't display
}
hasOff = true;
if (off !== searchData[6]) {
hasOff = false; //Doesn't match - don't display
}
// If either position or office matched then display the row
return true ? hasPosition || hasOffice || hasOff : false;
});
I have a view and tried to show it directly in a popup by clicking from a webgrid... I get the following error:
jquery-3.2.1.min.js:4 GET http://localhost:54751/Facturas/Save/4176?_=1534975761119 500 (Internal Server Error)
My JS code:
<script>
$(document).ready(function () {
var oTable = $('#myDatatable').DataTable({
"ajax": {
"url" : '/Facturas/GetEmployees',
"type" : "get",
"datatype" : "json"
},
"columns": [
{ "data": "id_docto", "autoWidth": true },
{ "data": "id_Proveedor", "autoWidth" : true},
{ "data": "Nombre_Archivo", "autoWidth": true },
{ "data": "Ruta_Docto", "autoWidth": true },
{ "data": "id_tipo_docto", "autoWidth": true },
{ "data": "Estatus", "autoWidth": true },
{ "data": "Fecha", "autoWidth": true },
{
"data": "id_Proveedor", "width": "50px", "render": function (data) {
return '<a class="popup" href="/Facturas/Save/' + data + '">Editar</a>';
}
},
{
"data": "EmployeeID", "width": "50px", "render": function (data) {
return '<a class="popup" href="/Facturas/Delete' + data + '">Borrar</a>';
}
}
]
})
$('.tablecontainer').on('click', 'a.popup', function (e) {
e.preventDefault();
OpenPopup($(this).attr('href'));
})
function OpenPopup(pageUrl) {
debugger;
var $pageContent = $('<div/>');
$pageContent.load(pageUrl, function () {
$('#popupForm', $pageContent).removeData('validator');
$('#popupForm', $pageContent).removeData('unobtrusiveValidation');
$.validator.unobtrusive.parse('form');
});
$dialog = $('<div class="popupWindow" style="overflow:auto"></div>')
.html($pageContent)
.dialog({
draggable : false,
autoOpen : false,
resizable : false,
model : true,
title:'ActualizaciĆ³n de Datos',
height : 550,
width : 600,
close: function () {
$dialog.dialog('destroy').remove();
}
})
debugger;
$('.popupWindow').on('submit', '#popupForm', function (e) {
var url = $('#popupForm')[0].action;
$.ajax({
type : "POST",
url : url,
data: $('#popupForm').serialize(),
success: function (data) {
if (data.status) {
$dialog.dialog('close');
oTable.ajax.reload();
}
}
})
e.preventDefault();
})
$dialog.dialog('open');
}
})
</script>
My C# code:
[HttpGet]
public ActionResult Save(int id)
{
try
{
using (SiniestrosEntities dc = new SiniestrosEntities())
{
var v = dc.CAT_Doctos_Proveedores.Where(a => a.id_Proveedor == id).FirstOrDefault();
return View(v);
}
}
catch (Exception e)
{
return View("Login");
}
}
Does anyone have an idea why it does not return my view "Save" to my Popup?
I am using data tables. Currently, it is working as expected, hower I would like to have the Add and Remove Buttons have some sort of count. For example AddButton_0
How would I do this using Data Tables?
var url = "/ClientSetup/GetCatalogueContracts";
var contractsTable = $('#catalogueContractsTable').DataTable({
sAjaxSource: url,
columns: [
{ "data": "ID" },
{ "data": "Selected"},
{ "data": "Name"},
{ "data": "ContractType"},
{ "data": "StartDate"},
{ "data": "TerminationDate"},
{ "button": "Action" }
],
serverSide: true,
sDom: 't<"dt-panelfooter clearfix"ip>',
pageLength: pageSize,
bSort: false,
bLengthChange: false,
bSearch: true,
paging: true,
searching: true,
order: [[2, "asc"]],
language: {
emptyTable: "No contracts found.",
zeroRecords: "No contracts found.",
info: "_START_ to _END_ of _TOTAL_",
paginate: {
first: "First",
previous: "Previous",
next: "Next",
last: "Last"
}
},
columnDefs: [
{
targets: [0],
visible: false
},
{
targets: [1],
visible: false
},
{
targets: [2]
},
{
targets: [3],
sClass: "hidden-xs hidden-sm contractType"
},
{
targets: [4],
sClass: "hidden-xs fromDate"
},
{
targets: [5],
sClass: "hidden-xs terminationDate"
},
{
data: null,
targets: [6],
sClass: "updateTableRow text-center",
render: function ( data, type, full, meta )
{
var id = data["ID"];
return `<button class=\"btn btn-success br2 btn-xs fs12 table-btn button-selector-${id}\" id=\"AddContractBtn\">Add</button>`;
}
}
],
drawCallback: function( settings ) {
disableInvalidContracts();
},
autoWidth: false
});
// make sure already selected rows cannot be added again.
var excludeIds = getExcludeIds();
$.each(excludeIds, function() {
var button = $("#AddContractBtn.button-selector-" + this);
button.addClass("disabled");
button.prop('disabled', true);
});
}
#* Adding and Removing Data from both Tables *#
contractsTable.on('click', '#AddContractBtn', function () {
var $row = $(this).closest("tr");
#*Track Contract IDs that have been removed from the unselected table*#
var value = $('#exclude-ids').val();
var ids = getExcludeIds();
ids.push($row.attr('id'));
$('#exclude-ids').val(JSON.stringify(ids));
var addRow = contractsTable.row($row);
var data = addRow.data();
data.Selected = true;
selectedContractsTable.row.add(addRow.data()).draw( false );
setSelectedInputForContract('true', data.ID);
disableInvalidContracts();
});
selectedContractsTable.on('click', '#RemoveContractBtn', function () {
var $row = $(this).closest('tr');
var addRow = selectedContractsTable.row($row);
var data = addRow.data();
data.Selected = false;
addRow.data(data);
addRow.remove().draw();
#* Remove the Contract ID from the exclide ids hidden input*#
var value = $('#exclude-ids').val();
var ids = getExcludeIds();
ids = ids.filter(i => i !== $row.attr('id'));
$('#exclude-ids').val(JSON.stringify(ids));
setSelectedInputForContract('false', data.ID);
disableInvalidContracts();
});
I am looking for a way that I can add a Count for each of the buttons for example `AddButton_0 I am unsure if there is an option to use a count on DataTables. Or whether I could use JQuery?
Try this : you can have global variable and increment it for each access of button creation function. Click handler for add and remove button can be created with start with attribute selector in jquery.
See below code
var count = 0;
var url = "/ClientSetup/GetCatalogueContracts";
var contractsTable = $('#catalogueContractsTable').DataTable({
sAjaxSource: url,
columns: [
{ "data": "ID" },
{ "data": "Selected"},
{ "data": "Name"},
{ "data": "ContractType"},
{ "data": "StartDate"},
{ "data": "TerminationDate"},
{ "button": "Action" }
],
serverSide: true,
sDom: 't<"dt-panelfooter clearfix"ip>',
pageLength: pageSize,
bSort: false,
bLengthChange: false,
bSearch: true,
paging: true,
searching: true,
order: [[2, "asc"]],
language: {
emptyTable: "No contracts found.",
zeroRecords: "No contracts found.",
info: "_START_ to _END_ of _TOTAL_",
paginate: {
first: "First",
previous: "Previous",
next: "Next",
last: "Last"
}
},
columnDefs: [
{
targets: [0],
visible: false
},
{
targets: [1],
visible: false
},
{
targets: [2]
},
{
targets: [3],
sClass: "hidden-xs hidden-sm contractType"
},
{
targets: [4],
sClass: "hidden-xs fromDate"
},
{
targets: [5],
sClass: "hidden-xs terminationDate"
},
{
data: null,
targets: [6],
sClass: "updateTableRow text-center",
render: function ( data, type, full, meta )
{
var button = `<button class=\"btn btn-success br2 btn-xs fs12 table-btn button-selector-${id}\" id=\"AddContractBtn' + count + '\">Add</button>`;
count++; // increment count
var id = data["ID"];
return button;
}
}
],
drawCallback: function( settings ) {
disableInvalidContracts();
},
autoWidth: false
});
// make sure already selected rows cannot be added again.
var excludeIds = getExcludeIds();
$.each(excludeIds, function() {
var button = $("#AddContractBtn.button-selector-" + this);
button.addClass("disabled");
button.prop('disabled', true);
});
}
#* Adding and Removing Data from both Tables *#
contractsTable.on('click', 'button[id^=AddContractBtn]', function () {
var $row = $(this).closest("tr");
#*Track Contract IDs that have been removed from the unselected table*#
var value = $('#exclude-ids').val();
var ids = getExcludeIds();
ids.push($row.attr('id'));
$('#exclude-ids').val(JSON.stringify(ids));
var addRow = contractsTable.row($row);
var data = addRow.data();
data.Selected = true;
selectedContractsTable.row.add(addRow.data()).draw( false );
setSelectedInputForContract('true', data.ID);
disableInvalidContracts();
});
selectedContractsTable.on('click', 'button[id^=RemoveContractBtn]', function () {
var $row = $(this).closest('tr');
var addRow = selectedContractsTable.row($row);
var data = addRow.data();
data.Selected = false;
addRow.data(data);
addRow.remove().draw();
#* Remove the Contract ID from the exclide ids hidden input*#
var value = $('#exclude-ids').val();
var ids = getExcludeIds();
ids = ids.filter(i => i !== $row.attr('id'));
$('#exclude-ids').val(JSON.stringify(ids));
setSelectedInputForContract('false', data.ID);
disableInvalidContracts();
});
I have created a jquery grid and loaded the json data into it.. And i have some radiobuttons on pop up.. based on that selection the json value is changed. For the first time , the json is loaded into gqgrid. but when i select other radio button the json value is changed but that new json is not loaded into jqgrid. The old json is showing.
I have tried ,
obj.datatype = "local";
obj.viewrecords = true;
obj.rowNum = 20;
obj.pager = "#jqGridPager";
obj.data = jsonValue;
obj.localReader = {repeatitems: true};
obj.rowList = [20,30,50];
obj.loadonce = true;
obj.colModel = [
{ "label": 'Id', "name": 'studentId', "width": "150" , "key" : true},
{ "label": 'No', "name": 'studentNo', "width": "150"},
{ "label": 'Name', "name": 'studentName', "width": "150"},
{ "label": 'Phone', "name": 'studentPhone', "width": "150"},
{ "label":'Email', "name": 'primaryContactEmail', "width": "150" },
{ "label":'Address', "name": 'studentAddress', "width": "150" }
];
obj.multiselect = true;
obj.navOptions = { reloadGridOptions: { fromServer: true } };
//console.log(obj)
$("#grid_json").jqGrid(obj).jqGrid('filterToolbar').navGrid('#jqGridPager',
{ edit: false, add: false, del: false, search: true, refresh: true, view: true, position: "left", cloneToTop: true },
{
editCaption: "The Edit Dialog",
recreateForm: true,
checkOnUpdate : true,
checkOnSubmit : true,
closeAfterEdit: true,
errorTextFormat: function (data) {
return 'Error: ' + data.responseText
}
},
// options for the Add Dialog
{
closeAfterAdd: true,
recreateForm: true,
errorTextFormat: function (data) {
return 'Error: ' + data.responseText
}
},
// options for the Delete Dailog
{
errorTextFormat: function (data) {
return 'Error: ' + data.responseText
}
},
{
multipleSearch: true
}
)
// add first custom button
/* $('#grid_json').navButtonAdd('#jqGridPager',
{
buttonicon: "ui-icon-mail-closed",
title: "Send Mail",
caption: "Send Mail",
position: "last",
// onClickButton: customButtonClicked
}); */
/// add second custom button
$('#grid_json').navButtonAdd('#jqGridPager',
{
buttonicon: "ui-icon-pencil",
title: "Edit",
caption: "Edit",
position: "last",
//onClickButton: customButtonClicked
});
Try this first clear the grid data then reset the data property of the grid options to your new json data.
var grid = $("#grid_json");
grid.jqGrid('clearGridData').jqGrid('setGridParam', {
data: new_data
}).trigger('reloadGrid', [{ page: 1 }]);