JQuery UI - Form doesn't open if autoOpen: false - javascript

I am using JQuery UI and I have a dialog box that I want to appear when a button is clicked. When autoOpen is set to true, it will display as soon as page loads and it will open and close. If it is set to false it will not open at all.
The JQuery UI code is at the bottom of this code block
$(document).ready(function () {
retrieveNotes().done(function (data) {
$.each(data.d, function (i, item) {
DataArray[i] = [];
DataArray[i][0] = item.NotesID.trim();
DataArray[i][1] = item.NotesTitle.trim();
DataArray[i][2] = item.NotesText.trim();
DataArray[i][3] = item.ProfileName.trim();
DataArray[i][4] = item.IsShared;
DataArray[i][5] = item.NameOfUser.trim();
});
// GRID LOGIC HERE
var tbl = $("#notes_table");
var obj = $.paramquery.tableToArray(tbl);
var newObj = {
width: 720, height: 300, sortIndx: 0,
editable: false,
flexHeight: false,
title: "Here are your notes for this profile</b>",
freezeCols: 1, resizable: false, selectionModel: { type: 'row' }, editModel: { clicksToEdit: 2 },
selectionModel: { mode: 'single' }
};
// MUST DECLARE CORRECT NUMBER OF COL PROPERTIES OTHERWISE NULL REFERENCE
obj.colModel = [
{ title: "Note ID", width: 50, dataType: "string" },
{ title: "Note Title", width: 255, dataType: "string" },
{ title: "Note Text", width: 255, dataType: "string" },
{ title: "Name of Profile", width: 200, dataType: "string" },
{ title: "Is Shared Profile", width: 10, dataType: "boolean" },
{ title: "Note created by:", width: 255, dataType: "string" },
];
newObj.dataModel = { data: DataArray, paging: "local", rPP: 15, rPPOptions: [10, 15, 20, 50, 100] };
newObj.colModel = obj.colModel;
//Hide GUID column from user but have it on DOM for edit/delete commands
newObj.colModel[0].hidden = true;
newObj.colModel[1].width = 255;
newObj.colModel[2].hidden = true;
newObj.colModel[3].width = 200;
newObj.colModel[4].width = 10;
newObj.colModel[5].width = 255;
//append or prepend the CRUD toolbar to .pq-grid-top or .pq-grid-bottom
$("#divGrid").on("pqgridrender", function (evt, obj) {
var $toolbar = $("<div class='pq-grid-toolbar pq-grid-toolbar-crud'></div>").appendTo($(".pq-grid-top", this));
$("<span>Add</span>").appendTo($toolbar).button({ icons: { primary: "ui-icon-circle-plus" } }).click(function (evt) {
addRow();
});
$("<span>Edit</span>").appendTo($toolbar).button({ icons: { primary: "ui-icon-pencil" } }).click(function (evt) {
editRow();
});
$("<span>Delete</span>").appendTo($toolbar).button({ icons: { primary: "ui-icon-circle-minus" } }).click(function () {
deleteRow();
});
$toolbar.disableSelection();
});
$grid = $("#divGrid").pqGrid(newObj);
//create popup dialog.
$("#popup-dialog-crud").dialog({
width: 400, modal: true,
open: function () { $(".ui-dialog").position({ of: "#divGrid" }); },
autoOpen: false
});
//buildGrid(DataArray);
});
});
My HTML
<div id="popup-dialog-crud" style="width: auto; min-height: 47px; height: auto;" class="ui-dialog-content ui-widget-content" scrolltop="0" scrollleft="0">
<form id="crud-form">
<table align="center">
<tbody>
<tr>
<td class="label">Company Name:</td>
<td>
<input type="text" name="company"></td>
</tr>
<tr>
<td class="label">Symbol:</td>
<td>
<input type="text" name="symbol"></td>
</tr>
<tr>
<td class="label">Price:</td>
<td>
<input type="text" name="price"></td>
</tr>
<tr>
<td class="label">Change:</td>
<td>
<input type="text" name="change"></td>
</tr>
<tr>
<td class="label">%Change:</td>
<td>
<input type="text" name="pchange"></td>
</tr>
<tr>
<td class="label">Volume:</td>
<td>
<input type="text" name="volume"></td>
</tr>
</tbody>
</table>
</form>
</div>

You can simply do this:
$( "#opener" ).click(function() {
$( "#popup-dialog-crud" ).dialog( "open" );
});
FIDDLE DEMO

Related

DataTables sorting for category name column doesn't work

Here is HTML code
<table id="datatable-language" class="table table-hover datatable-highlight">
<thead>
<tr>
<th></th>
<th>image</th>
<th>category_name</th>
<th>status</th>
<th></th>
<th></th>
</tr>
</thead>
</table>
Here is the JS code inside Datatable
columns: [
{
title: `<input type="checkbox" class="styled" onchange='toggleSelectAll(this);'>`,
orderable: false,
data: "category_id",
width: "50px"
},
{
data: "image",
render: function (data, type, row) {
return `<img src="${row['image']}" height="50px">`;
},
width: "100px"
},
{
data: "name",
ordering: true,
render: function (data, type, row) {
return `${row['name']}`;
}
},
{
data: "cstatus",
width: "30px"
},
{
width: "30px",
data: "category_id"
},
{
width: "10px",
data: "category_id"
},
],
columnDefs: [
{
targets: 1,
orderable: true
},
{
targets: 2,
orderable: true
},
{
orderable: false,
className: 'select-checkbox',
targets: 0
},
{
targets: 3,
render: function (data, type, row) {
var status = (data == "1" ? 'checked="checked"' : '');
return statusSwitch(row.category_id, status);
}
},
{
targets: 4,
orderable: false,
selectable: false,
visible: true,
render: function (data, type, row) {
return `<a data-popup="tooltip" title="${locales['text_preview']}" target="_blank" href="{{ linkfront('product/category', 'path=') }}${row['category_id']}" class='text-default'><i class='fa fa-eye fa-lg valign-middle'></i></a>`;
}
},
{
targets: 5,
orderable: false,
render: function (data, type, row) {
return `<ul class="icons-list pull-right">
<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown">
<i class="icon-menu9"></i>
</a>
<ul class="dropdown-menu dropdown-menu-right">
<li><a href='{{ link('catalog/category/update') }}?category_id=${row['category_id']}'><i class='icon-pencil7'></i> ${locales['button_edit']}</a></li>
<li><a onclick="removeItem(${row['category_id']})"><i class='icon-trash'></i> ${locales['button_delete']}</a></li>
</ul>
</li>
</ul>
`;
}
}
]
As you see, I make the orderable attr to true and the category_name still not working. Is there's a missing property of config?!
so what is the problem? the rest of the code doesn't make sense at all. I attached the snippets that make the table configurations
{
data: "name",
ordering: true,
render: function (data, type, row) {
return `${row['name']};
}
you write this
change data:"name" to data:"category_name"
and also return
${row['name']};
here change name to category_name
Take a look at the columns.render docs > https://datatables.net/reference/option/columns.render, especially the type param.
Your problem is that DT will sort the columns rendered markup, not the name value itself. So pass back the name value for sorting, markup for everything else:
render: function (data, type, row) {
return type == 'sort'
? row['name']
: `${row['name']};
}

How to load extra Javascript in Datatable Server Side processing?

I am using Datatable.net 1.10, with server processing. It is all good and working fine, but I can't get other javascript to work in the datatable. For example I was using tippy.js to generate nice tooltip in the table. This was working fine with client-side processing but javascript is totally ignored while using server-side processing.
Here is the Javascript I am using for the datatable (shortenened a bit):
function myDataTableAjax_Accident(id, actionURL) {
var areaDDL = document.getElementById('_AreaDDl');
var areaID = areaDDL.options[areaDDL.selectedIndex].value;
var incidentStatusDDL = document.getElementById('_IncidentStatus');
var incidentStatusID = incidentStatusDDL.options[incidentStatusDDL.selectedIndex].value;
var incidentKind = document.getElementById('incidentKind').value;
$('#' + id).DataTable({
dom: //cut for shortness
, serverSide: true
, processing: true
, pageLength: 100
, deferRender: true
, ajax: {
url: actionURL,
type: 'POST',
contentType: "application/json",
data: function (model) {
return JSON.stringify(model);
},
},
columns: [
{ data: null, defaultContent: "" },
{ data: "incident_EHSconnect_ID" },
{
data: "accident_type_name", defaultContent: defaultValueTxt
},
{ data: "incident_category", defaultContent: "" },
{ data: "incident_area_name", defaultContent: "" },
{ data: "location", defaultContent: defaultValueTxt },
{ data: "incident_description", defaultContent: "" },
{
data: null,
defaultContent: "",
orderable: false,
render: function (data, type, row, meta) {
var btns =
'<button id="' + data.incident_ID + '" data-id="' + data.incident_ID + '" class="modalDetails btn btn-default btn-control col-md-6 tip" title="Shows details of the accident" ><span class="glyphicon glyphicon-modal-window "></span> Details</button>' +
'<span class="glyphicon glyphicon-edit"></span> Edit ' +
'<span class="glyphicon glyphicon-download"></span> PDF'
;
if (!data.signed_by_injured_party) {
btns += '<span class="glyphicon glyphicon-pencil"></span> Sign';
}
return btns;
}
},
],
columnDefs: [{
className: 'control',
orderable: false,
targets: 0
}],
});
}
And here is the view:
#using AspMvcUtils
#using EHS.Utils
<table class="table table-bordered tblAccident" style="margin-top: 0px !important; width: 100%;" id="tblAccident">
<thead class="scrollStyle">
<tr>
<th></th>
<th>ID</th>
<th>Type</th>
<th>Category</th>
<th>Location</th>
<th>Exact Location</th>
<th>Description</th>
<th>Reported by</th>
<th>Reported Date</th>#*6*#
<th>Incident status</th>
<th data-priority="-1" class="col-md-6" style="max-width:150px;">Controls</th>
</tr>
</thead>
#*Rows -------------------------------------------------------------------------------------------------------*#
<tbody class="scrollStyle"> </tbody>
</table>
<div id="modalContainer" class="col-lg-12 col-md-12 col-sm-12 col-xs-12"></div>
<script>
tooltip('.tip', 'ehs');
$(document).ready(function () {
myDataTableAjax_Accident('tblAccident', '#Url.Action("DatatableServerSideIndex")');
});
</script>
And here is the tooltip function:
function tooltip(selector, userTheme) {
tippy(selector, {
theme: userTheme,
position: 'right',
animation: 'scale',
duration: 600
})
}
(I am using ASP.NET MVC4 by the way).
How can I get the extra javascript to work properly in the table?
You have to call tooltip after datatables complete its initialization, you can use fnInitComplete callback to do that:
$(document).ready( function() {
$('#example').dataTable({
...,
"fnInitComplete": function(oSettings, json) {
alert( 'DataTables has finished its initialisation.' );
// call tooltip here
tooltip('.tip', 'ehs');
}
});
});
Because you are using datatables and tooltip in 2 separate functions you can use callbacks to call them in order:
myDataTableAjax_Accident function:
function myDataTableAjax_Accident(id, actionURL, done) {
...,
"fnInitComplete": function(oSettings, json) {
done();
}
}
And then in your View you can pass done parameter as a function and then call tooltip like this:
<script>
$(document).ready(function () {
myDataTableAjax_Accident('tblAccident', '#Url.Action("DatatableServerSideIndex")', function() {
tooltip('.tip', 'ehs');
});
});
</script>

ajax.reload not working second time

I am using datatables in mu MVC application, i want to refresh my table everytime i edit any record through model popup.
it works one repord only, when i open model popup second time to edit same / other records it doesn't.
please help, here is my code.
<div class="tablecontainer">
<table id="schoolsTable" class="table table-bordered table-condensed table-hover table-striped">
<thead>
<tr>
<th>
Status
</th>
<th>
Code
</th>
<th>
Name
</th>
<th>
Address
</th>
<th>
Actions
</th>
</tr>
</thead>
</table>
</div>
<link href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css" rel="stylesheet" />
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/datatables/1.10.12/css/dataTables.bootstrap.min.css">
#section Scripts{
<script src="~/Content/datatables/datatables.min.js"></script>
<script src="assets/lib/jquery/jquery.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.0/jquery-ui.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/datatables/1.10.12/js/jquery.dataTables.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/datatables/1.10.12/js/dataTables.bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.tablesorter/2.26.6/js/jquery.tablesorter.min.js"></script>
<script>
$(document).ready(function () {
var oTable = $('#schoolsTable').DataTable({
"ajax": {
"url": "/School/viewschool",
"type": "Get",
"datatype": "json"
},
"columns": [
{ "data": "Mas_SchoolStatusID", "autowidth": true },
{ "data": "SchoolCode", "autowidth": true },
{ "data": "SchoolName", "autowidth": true },
{ "data": "SchoolAddress", "autowidth": true },
{
"data": "Mas_SchoolID", "width": "50px", "render": function (data) {
return '<a class="popup" href=/School/Edit/' + data +'>Edit</a>';
}
}
]
});
$('.tablecontainer').on('click', 'a.popup', function (e) {
e.preventDefault();
OpenPopup($(this).attr('href'))
})
function OpenPopup(pageUrl)
{
var $pageContent = $('<div/>');
$pageContent.load(pageUrl);
$dialog = $('<div class="popupWindow" style="overflow:auto"></div>')
.html($pageContent)
.dialog({
dragable: false,
autoOpen: false,
resizeable: false,
model: true,
title: 'Popup Dialog',
height: 550,
width: 600,
close: function () {
$dialog.dialog('distroy').remove();
}
})
$('.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) {
oTable.ajax.reload();
$dialog.dialog('close');
}
}
})
e.preventDefault();
})
$dialog.dialog('open');
}
});
</script>
}
i misspelled in destroy in close function as distroy.
close: function () {
$dialog.dialog('distroy').remove();
}
which should be:
close: function () {
$dialog.dialog('destroy').remove();
}

Calling href with Angular to open modal

Context
I´m working in this Tutorial, is about CRUD with DataTable, but difference I´m using Asp.Net WebApi with Angular
I´m into step 9, where tutorial made partial views for pop-up window, but I don´t use partial view, instead it, I use Angular Views
Problem
I don´t know how to replace that partial View for my Angular View
Code
View
<table class="table table-striped table-hover table-bordered dt-bootstrap no-footer" id="tabla_catalogos" role="grid" aria-describedby="sample_editable_1_info">
<thead>
<tr>
<th class="hidden"></th>
<th style="width: 200px;"> Codigo </th>
<th> Nombre </th>
</tr>
</thead>
<tbody></tbody>
</table>
JS
$('#tabla_catalogos')
.DataTable({
searching: true,
dom: 'ftpB',
autoWidth: false,
buttons: [
//'excelHtml5', 'csv', 'print'
],
paging: true,
select: {
style: 'single'
},
info: false,
ordering: true,
"processing": true,
ajax: {
method: 'GET',
url: "../../api/Catalogo/GetCatalogoRegistro/" + selected.ID,
dataSrc: '',
beforeSend: function(request) {
request.setRequestHeader("Version", $scope.usuario.Version);
request.setRequestHeader("Origen", 'Web');
}
},
columns: [
{ data: 'Catalogo', visible: false, searchable: false },
{ data: 'Codigo' },
{ data: 'ID', visible: false, searchable: false },
{ data: 'Nombre' },
{ data: 'Padre', visible: false, searchable: false },
{
data: 'ID',
render: function(data){
return '<a class="popup" href="root.detalleregistros'+data+'">Editar</a>';
}
},
{
data: 'ID',
render: function (data) {
return '<a class="popup" href="root.detalleregistros' + data + '">Eliminar</a>';
}
}
],
pageLength: 10 //,
//pagingType: "simple_numbers"
,
language: {
"emptyTable": "No se encontraron registros",
"zeroRecords": "No encontraron coincidencias",
"search": "Buscar: "
}
});
$('.tablecontainer').on('click', 'a.popup', function (e) {
e.preventDefault();
OpenPopup($(this).attr('href'));
});
function OpenPopup(pageUrl) {
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: 'Popup Dialog',
height: 550,
width: 600,
close: function () {
$dialog.dialog('destroy').remove();
}
})
$('.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');
}
};
Angular Service, invoke view:
.state('root.detalleregistros', {
url: "detalleRegistros.html",
templateUrl: "../SPA/administrador/catalogos/detalleRegistros.html",
controller: "detalleRegistrosCtrl",
authenticate: true
})
When I clic into url as mi code '<a class="popup" href="root.detalleregistros'+data+'">Editar</a>'; it redirect me to http://localhost:55720/admin/root.detalleregistros/1
instead
http://localhost:55718/admin/#/detalleRegistros.html
What I´am doing wrong there? help is very appreciated. Regards
I try '<a class="popup" ui-sref="root.detalleregistros({data:11})">Editar</a>'; as #Agam Banga comment but modal just don´t open, I need to add something to table view? or what can be wrong there?
You have defined the state for "root.detalleregistros". To Open this state, you need to use the inbuild directive of ui-router which is ui-sref.
<a ui-sref="root.detalleregistros">Editar</a>
Also, if you want to pass params, you can use
<a ui-sref="root.detalleregistros({data:11})">Editar</a>

Display jQuery DataTables with Ajax data source in a popup

I am trying to give a list in a popup according to Ajax request. Before Ajax request , list is in popup but after Ajax request, list stay in the page instead of popup and also there is the old list in the popup window. Here is the codes
<script>
function CreateMap() {
var chart = AmCharts.makeChart("piechartdiv", {
"type": "pie",
"theme": "light",
"fontFamily":"Calibri",
"dataProvider": [{
"product":"Following",
"value": #following,
"color": "#009688"
}, {
"product":"Not Following",
"value": #notFollowing ,
"color": "#555555"
}],
"legend": {
"align" : "right",
"fontSize" : 14
},
"marginLeft":-100,
"marginTop":-45,
"marginBottom":0,
"labelsEnabled":false,
"colorField": "color",
"valueField": "value",
"titleField": "product",
"outlineAlpha": 0.4,
"depth3D": 15,
"balloonText": "[[title]]<br><span style='font-size:14px'><b>[[value]]</b> ([[percents]]%)</span>",
"angle": 20,
"export": {
"enabled": true
}
});
jQuery('.chart-input').off().on('input change', function () {
var property = jQuery(this).data('property');
var target = chart;
var value = Number(this.value);
chart.startDuration = 0;
if (property == 'innerRadius') {
value += "%";
}
target[property] = value;
chart.validateNow();
});
chart.addListener("clickSlice", function (event) {
if ( event.dataItem.title == 'Unfollowing')
{
document.getElementById("s_open").click();
}
});
}
var isAjax = #isAjax;
if(isAjax)
{
CreateMap();
}
else
{
AmCharts.ready(function () {
CreateMap();
});
}
}
<button id="s_open" class="s_open btn-default" style="display:none;">Open popup</button>
<div id="s_follow">
<div class="row" style="border-radius:5px; padding:20px; background-color:#fff;">
<table id="hostTable" class="table table-striped" cellspacing="0">
<thead>
<tr>
<th>Host Table</th>
</tr>
</thead>
<tbody>
#Html.Raw(comparedDataTable.ToString())
</tbody>
</table>
<button class="btn s_close btn-danger">Close</button>
</div>
<script>
$(document).ready(function () {
$('#hostTable').DataTable( {
dom: 'Bfrtip',
buttons: [
'excelHtml5',
'csvHtml5'
],
destroy: true,
} );
});
$(document).ready(function () {
// Initialize the plugin
$('#s_follow').popup({
color: 'black',
opacity: 0.5,
transition: '0.3s',
scrolllock: true
});
});
How can we put the list hostTable into popup after ajax request?
SOLUTION
Use onopen option to initialize the table, see the code below.
$(document).ready(function () {
$('#s_follow').popup({
color: 'black',
opacity: 0.5,
transition: '0.3s',
scrolllock: true,
vertical: "top",
onopen: function() {
// If table was initialized before
if ($.fn.DataTable.isDataTable('#hostTable')){
// Clear table
$('#hostTable').DataTable().clear();
}
$('#hostTable').DataTable( {
dom: 'Bfrtip',
buttons: [
'excelHtml5',
'csvHtml5'
],
destroy: true
});
}
});
});
DEMO
See this jsFiddle for code and demonstration.

Categories