Datatables initialization troubles - datatables

I'm trying to initialize my datatable, but there's no way.
I want to configure 2 things at the same time but I do not know where the problem is.
First:
$(document).ready(function() {
$('#example').DataTable({
"bFilter" : false,
"bLengthChange": false
});
});
Second:
$(document).ready(function() {
var table = $('#example').DataTable();
$('#example tbody').on( 'click', 'tr', function () {
if ( $(this).hasClass('selected') ) {
$(this).removeClass('selected');
}
else {
table.$('tr.selected').removeClass('selected');
$(this).addClass('selected');
}
} );
$('#button').click( function () {
table.row('.selected').remove().draw( false );
} );
} );
Either of the two separately work correctly, but if the together do not work.
I have try this:
$(document).ready(function() {
$('#example').DataTable({
"bFilter" : false,
"bLengthChange": false
});
var table = $('#example').DataTable();
$('#example tbody').on( 'click', 'tr', function () {
if ( $(this).hasClass('selected') ) {
$(this).removeClass('selected');
}
else {
table.$('tr.selected').removeClass('selected');
$(this).addClass('selected');
}
});
$('#button').click( function () {
table.row('.selected').remove().draw( false );
});
});
Where is the problem? How can I combine this two options?
SOLVED: One css file was delete.

Ok, now all is fine. I have just removed one css file. Thank you Just code 9. I have find the problem trying to make the snippet.

Related

To-dos don't update when I choose a to-do list

I have two components: TodoList and TodoListsList. They get their data from states in todos.js and todoLists.js modules accordingly. When I choose some to-do list, i.e mark it as active, TodoListsList is updated, but TodoLists isn't, thought the data is updated. Here's how I do it.
todoListsState and markAsActive() (todoLists.js):
import todos from '#/modules/todos.js'
// ... some code ...
const todoListsState = reactive({
todoLists: [],
todoListsAreLoading: false,
removedTodoListId: null,
editedTodoListId: null,
editedTodoListName: '',
baseTodoListsApiUrl: process.env.VUE_APP_BASE_TODO_LISTS_API_URL,
todoListCreationFormModalId: 'todoListCreationFormModal',
todoListNameChangeFormModalId: 'todoListNameChangeFormModal'
});
// ... some code ...
function markAsActive(value) {
let { close } = infoToast();
if (value) {
axios.post((todoListsState.baseTodoListsApiUrl + 'mark-as-active'), {
activatedTodoListId: value
}).then(function () {
getTodoLists();
const { getTodos } = todos();
getTodos();
}).catch(function () {
dangerToast('Failed to mark to-do list as active.');
}).finally(() => {
close();
});
}
}
todosState and getTodos() (todos.js):
const todosState = reactive({
todos: [],
activeTodoListId: 0,
removedTodoId: null,
editedTodoId: null,
editedTodoText: '',
todosAreLoading: false,
baseTodosApiUrl: process.env.VUE_APP_BASE_TODOS_API_URL,
todoAdditionFormModalId: 'todoAdditionFormModal',
todoEditFormModalId: 'todoEditFormModal'
});
// ... some code ...
async function getTodos() {
try {
todosState.todosAreLoading = true;
const response = await axios.get(todosState.baseTodosApiUrl);
todosState.activeTodoListId = response.data[0];
todosState.todos = response.data[1];
} catch (e) {
dangerToast('To-dos loading failed.');
} finally {
todosState.todosAreLoading = false;
}
}
How does todosState.todos look in console:
todosState.todos when Todos.vue is mounted:
It doesn't look like the array looses it's reactivity.
If you need something else to understand my question, feel free to ask. Help appreciated.
The problem is solved! I have just moved todosState out of
export default function () {}
and it works! Finally! This thread helped me a lot.

Single dropdown filtering for Datatable

I've been struggling for a few days now, trying to get a single dropdown to filter my table. Upon selection of the eraId, the columns should be refreshed to only show the columns of the selected eraId.
This is how my tables looks like:
I've read a lot of examples on Datatables website or forums but I can't seem to find something working.
I have managed to create a dropdown menu containing the different EraIds as filter (I have simplified the example below with only 3 eraIds) but after selecting an entry in the dropdown, the table gets empty and the column list is not refreshed.
I think the problem is that I first retrieve the columns names, based on the eraId and then draw the table accordingly, displaying only the resources from the specific eraId. I have tried several things but did not manage.
Ideally I should callback getPlayerResourceTable with the selected eraId or update the column list with the resources on the selected eraId.
Javascript:
var columns = [];
function getPlayerResourceTable($selectedEraId) {
$.ajax({
type: "POST",
url: "./graphs.php",
data: { call_function : 'getResourceTableColumns', eraId: $selectedEraId},
success: function (data) {
data = JSON.parse(data);
columnNames = Object.keys(data.data);
for (var i in data.data) {
columns.push({data: data.data[i],
title: data.data[i]});
}
$('#playerResourceTable').DataTable( {
processing: true,
serverSide: false,
filter: true,
columns: columns,
ajax: {
url: './graphs.php',
type: 'POST',
data: { call_function: 'playerResourceTable', column_fields : data.data, eraId: $selectedEraId}
},
initComplete: function () {
this.api().columns( 0 ).every( function () {
var column = this;
var select = $('<select><option value=""></option></select>')
.appendTo( $("#playerResourceTablesWrapper .dataTables_filter"))
.on( 'change', function () {
var val = $.fn.dataTable.util.escapeRegex(
$(this).val()
);
column.search( this.value ).draw();
} );
select.append( '<option value="1">Era 1</option>' )
select.append( '<option value="2">Era 2</option>' )
select.append( '<option value="3">Era 3</option>' )
} );
}
});
}
});
}
$(document).ready(function() {
$selectedEraId = 1;
getPlayerResourceTable($selectedEraId);
} );
PHP:
getResourceTableColumns returns the column list with query similar to SELECT columnName FROM ages WHERE eraId = ?
playerResourceTable returns the resources for each column (type of resource) with query similar to SELECT ".$field_list." FROM user_resources
I also thought of removing WHERE eraId = ? in my MySQL query and filtering the columns on the client side but no luck either.
I eventually ended up separating both functions and destroying/re-creating the table when changing Era.
function getColumns($selectedEraId) {
var columns = [];
$.ajax({
type: "POST",
url: "./graphs.php",
data: { call_function : 'getResourceTableColumns', eraId: $selectedEraId},
success: function (data) {
data = JSON.parse(data);
for (var i in data.data) {
columns.push({data: data.data[i],
title: data.data[i]});
}
if ( $.fn.dataTable.isDataTable( '#playerResourceTable' ) ) { // If the table already exists, detroy it before creating it again
$('#playerResourceTable').DataTable().destroy();
}
getPlayerResourceTable($selectedEraId, columns); // Will recreate the table with the new columns
}
});
}
function getPlayerResourceTable($selectedEraId, columns_to_show) {
$city_id = 91;
$playerResourceTable = $('#playerResourceTable').DataTable( {
processing: true,
serverSide: false,
filter: true,
columns: columns_to_show,
ajax: {
url: './graphs.php',
type: 'POST',
data: { call_function: 'playerResourceTable', column_fields : columns_to_show, city_id : parseInt($city_id)}
},
initComplete: function () {
this.api().columns( 0 ).every( function () {
var column = this;
var select = $('<select id="selectEraId" ><option value=""></option></select>')
.appendTo( $("#playerResourceTablesWrapper .dataTables_filter"))
.on( 'change', function () {
var val = $.fn.dataTable.util.escapeRegex(
$(this).val()
);
column.search( this.value ).draw();
} );
dropdown_string = getEraDropdown($selectedEraId);
} );
$('#selectEraId').on('change', function() {
$selectedEraId = this.value;
columns_to_show = getColumns($selectedEraId);
});
}
});
}

Inheritance for durandal (HotTowel) viewmodels?

Simple question, pretty sure it's a complicated answer :)
Is it possible to implement some form of inheritance for viewmodels in Durandal?
So if you have a viewmodel something like this:
define(['durandal/app', 'services/datacontext', 'durandal/plugins/router', 'services/logger'],
function (app, datacontext, router, logger) {
var someVariable = ko.observable();
var isSaving = ko.observable(false);
var vm = {
activate: activate,
someVariable : someVariable,
refresh: refresh,
cancel: function () { router.navigateBack(); },
hasChanges: ko.computed(function () { return datacontext.hasChanges(); }),
canSave: ko.computed(function () { return datacontext.hasChanges() && !isSaving(); }),
goBack: function () { router.navigateBack(); },
save: function() {
isSaving(true);
return datacontext.saveChanges().fin(function () { isSaving(false); })
},
canDeactivate: function() {
if (datacontext.hasChanges()) {
var msg = 'Do you want to leave and cancel?';
return app.showMessage(msg, 'Navigate Away', ['Yes', 'No'])
.then(function(selectedOption) {
if (selectedOption === 'Yes') {
datacontext.cancelChanges();
}
return selectedOption;
});
}
return true;
}
};
return vm;
//#region Internal Methods
function activate(routeData) {
logger.log('View Activated for id {' + routeData.id + '}, null, 'View', true);
});
}
//#endregion
function refresh(id) {
return datacontext.getById(client, id);
}
});
Is it possible to make that into some kind of base type and inherit further viewmodels from it, being able to extend the requires list and so on?
There is another question on this, but the viewmodels don't appear to be quite the same as the one's that I build for durandal/HotTowel.
Thanks.
I'm pretty sure this can be accomplished with jQuery's extend method. This just occurred to me, so there may be something that I'm missing, but a basic example would be something along the lines of:
basevm.js
... your mentioned viewmodel
inheritingvm.js
define(['basevm'], function (basevm) {
var someNewObservable = ko.observable();
var vm = $.extend({
someNewObservable : someNewObservable
}, basevm);
return vm;
});
Please let me know if this works. I just coded from the top of my head and it hasn't been tested.
Just based off what your saying I came up with this. Let me know if this works for you and if it doesn't then let me know what I did wrong.
Thanks.
viewmodelBase
define(['durandal/app', 'services/datacontext', 'durandal/plugins/router', 'services/logger'],
function (app, datacontext, router, logger) {
var vm = function () {
var self = this;
this.someVariable = ko.observable();
this.isSaving = ko.observable(false);
this.hasChanges = ko.computed(function () { return datacontext.hasChanges(); });
this.canSave = ko.computed(function () { return datacontext.hasChanges() && !self.isSaving(); });
};
vm.prototype = {
activate: function (routeData) {
logger.log('View Activated for id {' + this.routeData.id + '}', null, 'View', true);
},
refresh: function (id) {
return datacontext.getById(client, id);
},
cancel: function () {
router.navigateBack();
},
goBack: function () { router.navigateBack(); },
save: function() {
var self = this;
this.isSaving(true);
return datacontext.saveChanges().fin(function () { self.isSaving(false); })
},
canDeactivate: function() {
if (datacontext.hasChanges()) {
var msg = 'Do you want to leave and cancel?';
return app.showMessage(msg, 'Navigate Away', ['Yes', 'No'])
.then(function(selectedOption) {
if (selectedOption === 'Yes') {
datacontext.cancelChanges();
}
return selectedOption;
});
}
return true;
}
};
return vm;
});
parent viewmodel
define([viewmodelBase], function (vmbase) {
var vm1 = new vmbase();
vm1.newProperty = "blah";
var vm2 = new vmbase();
});
I wrote a post on my blog that addresses this issue. In short, I use prototypical inheritance for all of my modal dialog views in one of my projects. Here's the link to the post I wrote (feel free to skip to the code part) and a jsFiddle example that demonstrates it.
Simplified example that can work in Durandal (NOTE: each view-model returns its constructor function, not an object):
viewmodels/modal.js
define(['durandal/system'],
function(system) {
var modal = function () {
this.name = 'Modal';
}
modal.prototype = {
activate: function() {
system.log(this.name + ' activating');
},
attached: function(view) {
system.log(this.name + ' attached');
},
deactivate: function() {
system.log(this.name + ' deactivating');
},
detached: function(view, parent) {
system.log(this.name + ' detached');
}
};
return modal;
});
viewmodels/child.js
define(['durandal/system', 'viewmodels/modal'],
function(system, Modal) {
var child = function() {
this.name = 'Child Modal';
}
// inherits from Modal
child.prototype = new Modal();
child.prototype.constructor = child;
child.prototype._super = Modal.prototype;
// overrides Modal's activate() method
child.prototype.activate = function() {
this._super.activate.call(this); // we can still call it from the _super property
system.log(this.name + ' activating [overridden version]');
};
return child;
});
I prefer this implementation because it supports code reuse, conforms to OOP principles as best as javascript allows, and it gives me the ability to call the base class' methods via the _super property when I need to. You can easily convert this as needed.

Jeditable + Datatables + Server Side Processing

I have this piece of code...
$(document).ready(function() {
var oTable = $('#example').dataTable( {
"bProcessing": true,
"bServerSide": true,
"sAjaxSource": "../listagem/listar_manuais.php",
"sPaginationType": "full_numbers",
"fnDrawCallback": function () {
$('td', this.fnGetNodes()).editable( 'update.php', {
"callback": function( sValue, y ) {
var aPos = oTable.fnGetPosition( this );
oTable.fnUpdate( sValue, aPos[0], aPos[1] );
},
"submitdata": function ( value, settings ) {
return { "row_id": this.parentNode.getAttribute('id') };
},
"height": "14px"
} );
}
});
} );
What it does is the server side search of Datatables...
My problem, is that i don't kno what to do from here, to get the Jeditable functional with the server side processing...
Can anyone help? :s
The values will be in the HTTP Request object in your update.php. Your updated value is in "value", row_id in "row_id" according to your code above.

Jquery animation-action after action

$(".Menu_Tab").live(
'mouseover',
function()
{
$(this).animate(
{"top": "130px"},
1000);
}
);
This is my code...as you can see "mouseover" changing the position of $(#.Menu_Tab).
My question is-If for example I want to change the color of $(#.Menu_Tab),but only
after the change of a position,how I'm doing that...
$(".Menu_Tab").live(
'mouseover',
function()
{
$(this).animate(
{"top": "130px"},
1000,
function() {
$(this).css("color", "blue");
}
);
}
);