Display Button on condition in Datatables with Cell Value - javascript

I have a Table using Datatables and the last column shows as default value a 0, but it can also show a value >=1 means, as long as it is having a 0 value, it shouldn't do anything, but once it is >=1 than I want to have a button displayed which picks a value from the Datatable and than opens a Modal.
Not sure how to get this Button thing done.
Below is my Datatable code incl. html.
// Manual Modal
$('#myModal').on('shown.bs.modal', function () {
$('#myInput').focus()
});
// Datatables Code
$(document).ready(function() {
$('#DTResTableList_1').DataTable({
"ajax": {
url: 'data.inc.php',
method: 'POST',
dataType: 'json',
contentType: 'application/json; charset=utf-8',
dataSrc: ""
},
paging: false,
scrollY: 400,
select: true,
'columns': [{
'data': 'TABLE_NUMBER'
},
{
'data': 'STATION'
},
{
'data': 'GUESTS'
},
{
'data': 'T_STATUS'
},
{
'data': 'MINUTES_SEATED'
},
{
'data': 'MINUTES_OVERDUE'
}
]
});
setInterval(function() {
$('#DTResTableList_1').DataTable().ajax.reload(null, false); // user paging is not reset on reload
}, 5000);
});
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" rel="stylesheet" />
<link href="https://cdn.datatables.net/1.10.13/css/jquery.dataTables.min.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/js/bootstrap.min.js"></script>
<script src="https://cdn.datatables.net/1.10.13/js/jquery.dataTables.min.js"></script>
<!-- Button trigger modal -->
<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#myModal">
Launch demo modal
</button>
<!-- Modal -->
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">Modal title</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
...
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary">Save changes</button>
</div>
</div>
</div>
</div>
<div class="container-fluid">
<table class="table table-sm table-striped table-hover" id="DTResTableList_1" style="width: 100%;">
<thead>
<tr>
<th class="" data-toggle="tooltip" data-placement="top" title="Table Number">Table</th>
<th class="" data-toggle="tooltip" data-placement="top" title="Waiterstation">Station</th>
<th class="" data-toggle="tooltip" data-placement="top" title="Guests on Table">G</th>
<th class="" data-toggle="tooltip" data-placement="top" title="Table Stauts">Status</th>
<th class="" data-toggle="tooltip" data-placement="top" title="Minutes Seated">Minutes</th>
<th class="" data-toggle="tooltip" data-placement="top" title="Overdue">Button</th>
</tr>
</thead>
</table>
</div>

Ok, here is one closer to what you asked for. Here is on that puts buttons in the last column if the employee is under 40. Again, the code gets the data for the row then displays the name of the employee. Notice how I used render in the columnDefs.
http://jsbin.com/gobonec/edit?js,output
$(document).ready(function () {
var table = $('#example').DataTable({
"data": dataStore.data,
"columns": [
{ "data": "name" },
{ "data": "age" },
{ "data": "position" },
{ "data": "office" },
{ "data": "extn" },
{ "data": "start_date" },
{ "data": "salary" },
{ "data": null },
],
columnDefs: [{
// puts a button in the last column
targets: [-1], render: function (a, b, data, d) {
if (data.age < 40) {
return "<button type='button'>Go</button>";
}
return "";
}
}],
});
table.on("click", "button",
function () {
alert(table.rows($(this).closest("tr")).data()[0].name);
});
});

From DataTables Callbacks:
fnCreatedRow:
This function is called when a TR element is created (and all TD child elements have been inserted), or registered if using a DOM source, allowing manipulation of the TR element (adding classes etc).
That means you can add such an option when creating DataTable:
"fnCreatedRow": function( nRow, aData, iDataIndex ) {
if (+aData.MINUTES_OVERDUE > 0) {
$(nRow).find('td:last')
.replaceWith('<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#myModal" val="'
+ aData.MINUTES_OVERDUE + '">Launch demo modal</button>');
}
},
And changing your modal shown.bs.modal handler to:
$('#myModal').on('shown.bs.modal', function (e) {
$('#myInput').val($(e.relatedTarget).attr('val')).focus();
});
Explanation:
whenever a row is created:
test the content of last element
if this is greater than 0 replace the table cell with a button having an attribute containing the value of interest
whenever the modal is shown:
get the attribute from the related button and put it into the input field
The event handler for shown.bs.modal must be inside the document ready.

I have a solution that uses the in row selector and button extensions. In my sample, if the user is older than 40 the button is both disabled and hidden. if they are younger, its displayed and enabled. Clicking on the button gets the data object and uses it to display the person's name
http://live.datatables.net/kudotiqu/1/edit
$(document).ready( function () {
var table = $('#example').DataTable({select:"single",dom:"tB",
buttons:[{text:"Do It",
extend:"selected",
action:function( e, dt, node, config){
alert( dt.rows({selected:true}).data()[0][0]);}}]
});
table.on( 'select', function ( e, dt, type, indexes ) {
var s = dt.settings();
var g = dt.rows(indexes).data()[0] ;
if(parseInt(g[3]) > 40) {
s.buttons().enable(false);
$(s.buttons()[0].node).css("display","none");
}
else {
s.buttons().enable(true);
$(s.buttons()[0].node).css("display", "");
}
 } );
});

Related

How to change data with Javascript as DataTables displays it into a html table

I am very new to Javascript, I am working to extend pieces of code implemented by third parts and I have to slightly change some data before it is displayed into a html table via DataTables.
In particular, data comes from the columns "nested field" and "subfields" of a Postgres database table, declared as:
CREATE TABLE testing_nested_field_blacklist (
nested_field varchar(100) NOT NULL UNIQUE,
subfields varchar(100)[] NOT NULL
);
The html table filled up with data looks like this:
Data coming from column "subfields" is displayed into the table as a string of words separated by commas (,), but what I want instead is words to be separated by comma and one space (, ) , like this:
In order to get this, I am thinking about
building a function that, given a string as input, substitutes
commas with comma-and-space and returns it as output
put the function in a for cycle that applyes the substitution to element of column "subfields"
for each row of the table, and I would put this function at the end of the script that loads
the data into the table. So that it gets triggered also when "refresh", "add", "edit" and
"delete" functions are triggered.
However, I don't know how to get and change the data.
Can anybody point me the right direction to do this?
This is the javascript piece of code that displays the data into the html template:
var NestedFieldTable;
var nested_field_to_remove = {};
var nested_field;
$(document).ready(function() {
// NESTED FIELD
NestedFieldTable = $('#NestedFieldTable').DataTable({
"destroy": true,
"processing":true,
"ajax": {
"url": '/getNestedFields/',
"type":"POST",
"dataSrc": "nested_field"
},
"columns": columns_nested_field,
"columnDefs": [
{"targets": -1, "data": null, "defaultContent": "<i class='fas fa-edit' aria-hidden='true' id='modifyRow' data-toggle='modal' data-target='#myModalEditNestedField' title='click to edit nested field or blacklist'></i><i style='margin-left:15px;' class='fas fa-trash' aria-hidden='true' id='deleteRow' data-toggle='modal' data-target='#myModalDeleteNestedField' title='Click to delete nested field and blacklist'></i>", "width": "75px"},
],
"dom": "<'row'<'col-md-6 toolbar_nestedfield'><'col-md-6'fBl>>" +
"<'row'<'col-md-6'><'col-md-6'>>" +
"<'row'<'col-md-12't>><'row'<'col-md-12'pi>>",
"buttons": [
{
extend: 'collection',
text: 'Export',
autoClose: true,
buttons: [
{
text: '<i class="fas fa-print"></i> Print',
extend: 'print',
messageTop: 'Table of subfields and nested field .',
footer: false
}
]
},
{
text: '<i class="fas fa-sync-alt"></i>',
titleAttr: 'Refresh table',
action: function ( e, dt) {
dt.ajax.reload();
set_alert_message({"title":"Refresh", "detail":"Table successfully refreshed"}, "success");
}
}
],
"language": {
"searchPlaceholder": "Search",
"search": "<div class='form-group'><div class='input-group'><div class='input-group-prepend'><span class='input-group-text'><i class='fas fa-search fa-fw'></i></span></div>_INPUT_</div></div>",
"lengthMenu": "<div class='form-group'><div class='input-group'><div class='input-group-prepend'><span class='input-group-text'><i class='fas fa-list-ul fa-fw'></i></span></div>_MENU_</div></div>",
"oPaginate": {
sNext: '<span class="pagination-default">❯</span>',
sPrevious: '<span class="pagination-default">❮</span>'
}
}
});
$(".toolbar_nestedfield").html('<button type="button" class="dt-button" title="click to add new nested field and blacklist" data-toggle="modal" data-target="#myModalAddNestedField"><i class="fas fa-plus"></i></button>');
This is the javascript piece of code that defines the columns of the tabel, and it is necessary to make DataTables work:
var columns_nested_field = [
{ "title":"Nested field", data: "nested_field"},
{ "title":"Subfields blacklist", data: "subfields"},
{ "title":"Edit", "orderable": false, "className": 'icon_dt_style'}
];
and this is the html template:
<!-- Begin Page Content -->
<div class="container-fluid">
<ol class="breadcrumb shadow-lg">
<li class="breadcrumb-item">
Home
</li>
<li class="breadcrumb-item active">Nested fields and subfields blacklists</li>
</ol>
<!-- alert messages -->
<div class="alert alert-success alert-dismissible fade show" role="alert">
<button type="button" class="close" data-dismiss="alert" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
<strong id="alert-success-title"></strong> <div id="alert-success-detail"></div>
</div>
<div class="alert alert-danger alert-dismissible fade show" role="alert">
<button type="button" class="close" data-dismiss="alert" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
<strong id="alert-danger-title"></strong> <div id="alert-danger-detail"></div>
</div>
<!-- TABELLA NESTED FIELDS -->
<div class="card shadow mb-4">
<div class="card-header py-3">
<h6 class="m-0 font-weight-bold text-primary"><i class="fas fa-ban" aria-hidden="true"></i> Nested fields and subfields blacklists</h6>
</div>
<div class="card-body">
<div class="table-responsive">
<table class="table table-bordered table-hover" id="NestedFieldTable" width="100%" cellspacing="0">
</table>
</div>
</div>
</div>
</div>
<!-- /.container-fluid -->
SOLVED
As suggested in the comments by #Lapskaus, data displayed by DataTables can be manipulated by using the columns.render method.
In my case I had to apply the same change to all elements of an array (having each cell of column subfields containing an array), so I used the Array-access render method.
I added the element key-value render: "[my-separator]" to object
{ "title":"Subfields blacklist", data: "subfields"}
of variable columns_nested_field, that corresponds to the column whose data I want to manipulate ("render": "[my-separator]" works as well).
And since I want , as separator, I turned my variable
var columns_nested_field = [
{ "title":"Nested field", data: "nested_field"},
{ "title":"Subfields blacklist", data: "subfields"},
{ "title":"Edit", "orderable": false, "className": 'icon_dt_style'}
];
into
var columns_nested_field = [
{ "title":"Nested field", data: "nested_field"},
{ "title":"Subfields blacklist", data: "subfields", render: "[, ]"}, // <-- added the render key
{ "title":"Edit", "orderable": false, "className": 'icon_dt_style'}
];
so that I get

Is there a possibility to bind the Form to a modal bootstrap window without using the load call?

I'm using ajax to make a request and open a modal bootstrap window afterwards. The problem is that when I use ajax, I make a request to my controller, and the return (modal content) I load as follows:
//modal loading
$('#contentModalFinanceiroParcela').html(data);
//exibição da modal
$('#modalFinanceiroParcela').modal({
keyboard: true,
}, 'show');
So far, everything perfect. The problem is that from then on, I can't bind the form to register the submit event of the form. In the function bindFormFinanceiroParcela, no matter how much I pass the "dialog", bind does not work.
bindFormFinanceiroParcela(document.getElementById("contentModalFinanceiroParcela"));
Searching the forums, I found that the process works if I load the modal using the "load" command, as below, but I can't do it like that, otherwise it will make a second request to the controller, because previously, I already used ajax .
//That way it works, but I can't use it.
$('#contentModalFinanceiroParcela').load(url, function () {
$('#modalFinanceiroParcela').modal({
keyboard: true
}, 'show');
// Inscreve o evento submit
bindFormFinanceiroParcela(this);
stopLoadPage();
});
Is there a possibility that I can bind the form without using the "load" command mentioned in the script above?
function openModalFinanceiroParcelaSemURL(data) {
startLoadPage();
//Create the modal window block in the body of the page
if (!$("#modalFinanceiroParcela").data('bs.modal'))
CreateModalFinanceiroParcela();
//Load modal content via ajax request
$('#contentModalFinanceiroParcela').html(data);
$('#modalFinanceiroParcela').modal({
keyboard: true,
}, 'show');
bindFormFinanceiroParcela(document.getElementById("contentModalFinanceiroParcela"));
stopLoadPage();
}
function bindFormFinanceiroParcela(dialog) {
$('form', dialog).submit(function (e, i) {
if ($(this).valid() || i) {
startLoadOneMoment();
$.ajax({
url: this.action,
type: this.method,
data: $(this).serialize(),
success: function (result) {
if (result.success) {
window.location = window.location;
} else {
$('#contentModalFinanceiroParcela').html(result);
bindFormFinanceiroParcela();
}
stopLoadOneMoment();
}
});
return false;
} else {
return false;
}
});
function CreateModalFinanceiroParcela() {
var html = '<div class="modal modal-primary modal-system" tabindex="-1" role="dialog" id="modalFinanceiroParcela" data-backdrop="static"><div class="modal-dialog modal-dialog-centered"><div class="modal-content"><div class="content-modal-system" id="contentModalFinanceiroParcela"></div></div></div></div>';
$("body").append(html);
}
RAZOR DELETE:
#using Retaguarda.Domain.Enuns
#model Retaguarda.Application.ViewModels.Financeiro.FinanceiroParcela.FinanceiroParcelaViewModel
#{
ViewData["Title"] = "Excluir Parcela";
Layout = null;
}
<div>
<form asp-action="Delete" id="frm-excluir-financeiro-parcela">
#Html.AntiForgeryToken()
<div class="modal-shadow">
<div class="modal-header modal-header-primary">
<button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">×</span><span class="sr-only">Close</span></button>
<h4><i class="modal-title text-center glyphicon glyphicon-trash"></i> #ViewData["Title"] </h4>
</div>
<div class="panel">
<div class="panel-body container-fluid pt-15 pl-15 pr-15">
<div class="form-horizontal">
<vc:summary />
<br />
<div class="message-delete">
#Html.HiddenFor(model => model.Id, new { id = "hid-financeiro-parcela-id" })
<i class="icon fa-trash" aria-hidden="true"></i>
<p>
Tem certeza de que deseja excluir a parcela #(Model.Parcela)?<br />
</p>
</div>
</div>
</div>
</div>
<div class="modal-footer">
<div class="col-md-offset-2 col-md-10">
<div class="float-right">
<div class="btn-group btn-group-sm mr-auto"
role="group">
<div class="btn-group btn-group-sm" role="group">
#*<button id="btn-excluir-financeiro-parcela" type="submit" class="btn btn-success"><i class="icon wb-check"></i> Excluir </button>*#
<button id="btn-excluir-financeiro-parcela" type="button" class="btn btn-success"><i class="icon wb-check"></i> Excluir </button>
<button id="btn-cancelar-financeiro-parcela" class="btn btn-danger" data-dismiss="modal"><i class="icon wb-close"></i> Cancelar </button>
</div>
</div>
</div>
</div>
</div>
</div>
</form>
</div>
<script src="~/lib/jquery-validation/dist/jquery.validate.js"></script>
<script src="~/lib/jquery-validation-unobtrusive/jquery.validate.unobtrusive.js"></script>
#section Scripts {
#{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
}
Ajax call
$('#dtFinanceiroParcela').on('click', 'tr .btn-excluir-financeiro-parcela', function (e) {
e.preventDefault();
startLoadOneMoment();
var id = $(this).attr('data-id');
var data = { id: id };
var dataURL = jQuery.param(data);
$.ajax({
url: "/financeiro-parcela-gerenciar/remover-financeiro-parcela/" + id,
type: "GET",
// data: dataURL,
contentType: "application/json",
async: false,
success: function (result) {
if (typeof result.success !== 'undefined') {
if (!result.success) {
stopLoadOneMoment();
swal("Oops", result.message, "error");
return false;
}
}
// alert(this.url);
stopLoadOneMoment();
openModalFinanceiroParcelaSemURL(result);
return false;
},
error: function () {
stopLoadOneMoment();
alert("Oops! Algo deu errado.");
return false;
}
});
Your form inside razor does not contain any submit button because its commented out.
#*<button id="btn-excluir-financeiro-parcela" type="submit" class="btn btn-success"><i class="icon wb-check"></i> Excluir </button>*#
Remove the comment or change the type of the other button to "submit"
I guess the submit event is attached successfully but never called due to the missing submit button inside your form.

"Uncaught TypeError: $(...).modal is not a function" when trying to open modal from Tabulator

This question has already been answered, but those answers don't work for me. I've already tried to update my dependencies and I've even added some.
I am using tabulator to do the management of the users. When I click a cell in tabulator, I want it to open a modal so that I can auto-populate it.
How can I open the modal on row/cell click? I know for the row click I am not using the right function, I am only using cell click for testing.
I'm getting the following error:
gestaoutilizadores:338 Uncaught TypeError: $(...).modal is not a function
at t.cellClick (gestaoutilizadores:338)
at HTMLDivElement. (tabulator.min.js:4)
Dependencies
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript" src="https://unpkg.com/tabulator-tables#4.4.3/dist/js/tabulator.min.js"></script>
Modal
<div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">Modal title</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
...
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary">Save changes</button>
</div>
</div>
</div>
</div>
Javascript (Tabulator)
var table = new Tabulator("#example-table", {
height: "100%", // set height of table (in CSS or here), this enables the Virtual DOM and improves render speed dramatically (can be any valid css height value)
data: tabledata, //assign data to table
layout: "fitColumns", //fit columns to width of table (optional)
pagination: "local", //enable local pagination.
paginationSize: 5, // this option can take any positive integer value (default = 10)
columns: [ //Define Table Columns
{
title: "ID",
field: "id",
width: 150
},
{
title: "Tipo Utilizador",
field: "type",
align: "center",
/*, align:"left", formatter:"progress"*/ formatter: "lookup",
formatterParams: {
"0": "Super User",
"1": "Admin",
"2": "Utilizador Normal",
}
},
{
title: "Username",
field: "username",
align: "center",
cellClick: function(e, cell) {
var data = cell.getData();
$('#exampleModal').modal('toggle');
console.log(data);
console.log("username")
},
},
{
title: "Password",
field: "password",
align: "center"
},
{
title: "Empresa",
field: "empresa",
align: "center"
},
{
title: "Data de Criacao",
field: "createDate",
sorter: "date",
align: "center"
},
],
});
You will need to import the jQuery library before the bootstrap library.
This is because the bootstrap library will register the modal plugin with jQuery when the package loads, if jQuery is not there when this happens then the modal plugin will not be loaded and your code will error.

How to position model dialog to the center?

I am new to mvc and im implimenting a small software in mvc. i used an online tutorial to model a view with model popup from a partial view. but the popups always appear to the right. i have tried many samples given here also it only change bit. inherit is affects more than absolute key word. im using bootstrap 3 templete which has a left side menu bar.
do we have to set position of the div also ?
do i have to insert some css to partial view ?
is there any way we can easitly correct these view related things other than testing example codes?
why the model position not comming to the middle ?
Thank a lot in advance.
<link href="#Url.Content("~/Content/themes/base/jquery-ui.css")" rel="stylesheet" type="text/css" media="all" />
<head>
<style src="https://cdn.datatables.net/1.10.16/css/jquery.dataTables.min.css"></style>
<style src="https://cdn.datatables.net/select/1.2.5/css/select.dataTables.min.css"></style>
<style src="https://cdn.datatables.net/responsive/2.2.1/css/responsive.dataTables.min.css"></style>
<style>
.modal {
position: absolute;
top: 10px;
right: 100px;
bottom: 0;
left:200px;
z-index: 10040;
overflow: auto;
overflow-y: auto;
}
</style>
</head>
<h2>Index</h2>
<p>
#Html.ActionLink("Create New", "Create")
</p>
< <div class="panel panel-default m-b-0">
<div class="form">
<div class="row">
<div class="col-md-12">
<div class="panel panel-primary list-panel" id="list-panel">
<div class="panel-heading list-panel-heading">
<h1 class="panel-title list-panel-title">Assets</h1>
<button type="button" class="btn btn-default btn-md" data-toggle="modal" data-target="#advancedSearchModal" id="advancedsearch-button">
<span class="glyphicon glyphicon-search" aria-hidden="true"></span> Advanced Search
</button>
<button type="button" class="btn btn-default btn-md" data-toggle="modal" data-url="#Url.Action("Create","POPM_Trn_IOU")" id="btnCreateAsset">
<span class="glyphicon glyphicon-new-window" aria-hidden="true"></span> Add Asset
</button>
</div>
<div class="panel-body">
<table id="assets-data-table" class="table table-striped table-bordered" style="width:100%;"></table>
</div>
</div>
</div>
</div>
<div class="modal fade" id="createAssetModal" tabindex="-1" role="dialog" aria-labelledby="CreateAssetModal" aria-hidden="true" data-backdrop="static">
<div id="createAssetContainer">
</div>
</div>
<div class="modal fade" id="editAssetModal" tabindex="-1" role="dialog" aria-labelledby="EditAssetModal" aria-hidden="true" data-backdrop="static">
<div id="editAssetContainer">
</div>
</div>
<div class="modal fade" id="detailsAssetModal" tabindex="-1" role="dialog" aria-labelledby="DetailsAssetModal" aria-hidden="true" data-backdrop="static">
<div id="detailsAssetContainer">
</div>
</div>
<div class="modal fade" id="deleteAssetModal" tabindex="-1" role="dialog" aria-labelledby="DeleteAssetModal" aria-hidden="true" data-backdrop="static">
<div id="deleteAssetContainer">
</div>
</div>
#*#Html.Action("AdvancedSearch")*#
<div class="panel-body">
<table id="assets-data-table" class="table table-striped table-bordered" style="width:100%;"></table>
</div>
</div>
</div>
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://cdn.datatables.net/1.10.16/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/fixedcolumns/3.2.4/js/dataTables.fixedColumns.min.js"></script>
<script src="https://cdn.datatables.net/select/1.2.5/js/dataTables.select.min.js"></script>
<script src="https://cdn.datatables.net/responsive/2.2.1/js/dataTables.responsive.min.js"></script>
<script src="https://cdn.datatables.net/keytable/2.3.2/js/dataTables.keyTable.min.js"></script>
#section scripts {
<script type="text/javascript">
var assetListVM;
$(function () {
assetListVM = {
dt: null,
init: function () {
dt = $('#assets-data-table').DataTable({
"serverSide": true,
"processing": true,
"ajax": {
"url": "#Url.Action("Index", "POPM_Trn_IOU")",
"data": function (data) {
data.FacilitySite = $("#FacilitySite").val();
data.Building = $("#Building").val();
data.Manufacturer = $("#Manufacturer").val();
data.Status = $("#Status").val();
}
},
"columns": [
{ "title": "S/N", "data": "BarCode", "searchable": true },
{ "title": "Code", "data": "Manufacturer", "searchable": true },
{ "title": "Description", "data": "ModelNumber", "searchable": true },
{ "title": "Requested Amount", "data": "Building", "searchable": true },
{ "title": "Expandable Amount", "data": "RoomNo" },
{ "title": "Balance Amount", "data": "Quantity" },
{ "title": "Total Expences", "data": "Quantity" },
{ "title": "Remarks", "data": "Quantity" },
{
"title": "Actions",
"data": "AssetID",
"searchable": false,
"sortable": false,
"render": function (data, type, full, meta) {
return 'Edit | Details | Delete';
}
}
],
"lengthMenu": [[10, 25, 50, 100], [10, 25, 50, 100]],
});
},
refresh: function () {
dt.ajax.reload();
}
}
// Advanced Search Modal Search button click handler
$('#btnPerformAdvancedSearch').on("click", assetListVM.refresh);
// initialize the datatables
assetListVM.init();
$("#btnCreateAsset").on("click", function () {
var url = $(this).data("url");
$.get(url, function (data) {
$('#createAssetContainer').html(data);
$('#createAssetModal').modal('show');
});
});
$('#assets-data-table').on("click", ".editAsset", function (event) {
event.preventDefault();
var url = $(this).attr("href");
$.get(url, function (data) {
$('#editAssetContainer').html(data);
$('#editAssetModal').modal('show');
});
});
$('#assets-data-table').on("click", ".detailsAsset", function (event) {
event.preventDefault();
var url = $(this).attr("href");
$.get(url, function (data) {
$('#detailsAssetContainer').html(data);
$('#detailsAssetModal').modal('show');
});
});
$('#assets-data-table').on("click", ".deleteAsset", function (event) {
event.preventDefault();
var url = $(this).attr("href");
$.get(url, function (data) {
$('#deleteAssetContainer').html(data);
$('#deleteAssetModal').modal('show');
});
});
});
/**** Create Asset Ajax Form CallBack ********/
function CreateAssetSuccess(data) {
if (data != "success") {
$('#createAssetContainer').html(data);
return;
}
$('#createAssetModal').modal('hide');
$('#createAssetContainer').html("");
assetListVM.refresh();
}
/**** Edit Asset Ajax Form CallBack ********/
function UpdateAssetSuccess(data) {
if (data != "success") {
$('#editAssetContainer').html(data);
return;
}
$('#editAssetModal').modal('hide');
$('#editAssetContainer').html("");
assetListVM.refresh();
}
/**** Delet Asset Ajax Form CallBack ********/
function DeleteAssetSuccess(data) {
if (data != "success") {
$('#deleteAssetContainer').html(data);
return;
}
$('#deleteAssetModal').modal('hide');
$('#deleteAssetContainer').html("");
assetListVM.refresh();
}
</script>
}
Add left, top, and transform to your modal.
.modal {
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
z-index: 10040;
overflow: auto;
overflow-y: auto;
}

Open dialog after closing another - populate dropdown with ajax call - jquery

I want to show a dialog with jquery after another dialog is closed.
Here is the first dialog
When I press the Close button another dialog needs to be showed. This dialog which has a drop down, and I need to populate this dropdown with ajax call.
The problem is that I keep get this error on console: TypeError: $(...).get(...) is undefined. and the method from the controller is never reached.
This is the code that I'm using:
<script type="text/javascript">
$("#saveGeometryType_dialog").draggable({ handle: ".modal-header" });
function saveElements(options) {
}
function closeDialog(options) {
var $temp = $("<input/>", { id: 'temp' });
//$temp.val($(options.element).text()).select();
//document.execCommand("copy");
//var title = $("#geometry-dialog").dialog("option", "title");
//console.log($temp);
$temp.remove();
var title = "Linestring";
$('#saveGeometryType_dialog').modal('show');
$.ajax({
type: "POST",
url: "PlotDescriptions/GetCodes/" + title,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
$("#ddlCode").get(0).options.length = 0;
$("#ddlCode").get(0).options[0] = new Option("Select code", "-1");
$.each(msg.d, function(index, item) {
$("#ddlCode").get(0).options[$("#ddlCode").get(0).options.length] = new Option(item.Display, item.Value);
});
},
error: function() {
$("#ddlCode").get(0).options.length = 0;
alert("Failed to load names");
}
});
}
</script>
<div class="modal fade" tabindex="-1" role="dialog" id="saveGeometryType_dialog">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title">Save geometry</h4>
</div>
<div class="modal-body">
<p></p>
<div class="saveGeometryType-header">
<div class="row">
<div class="col-md-4"> Cod </div>
<div class="col-md-4"> <select id="ddlCod">
</select> </div>
</div>
</div>
</div>
<div class="modal-footer">
<button onclick="saveElements({ 'element': '#saveGeometryType_dialog .modal-body > p', 'target': 'saveGeometryType_dialog .modal-body' });$('#saveGeometryType_dialog').modal('hide');" type="button" class="btn btn-primary">Save</button>
<button onclick="closeDialog({ 'element': '#saveGeometryType_dialog .modal-body > p', 'target': 'saveGeometryType_dialog .modal-body' });$('#saveGeometryType_dialog').modal('hide');" type="button" class="btn btn-default">Close</button>
</div>
</div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->
</div><!-- /.modal -->
This is the controller method that I need to reach. The parameter from the method should be the title from the first dialog, in this case the Linestring.:
[WebMethod]public static ArrayList GetCodes(string geometryType)
{
return new ArrayList()
{
new { Value = 1, Display = "Code1" },
new { Value = 2, Display = "Code2" }
};
}
Any help is appreciated.

Categories