How to get value from DataTables row on row click event - javascript

I have a HTML page with a DataTable (datatables.net) with data that is populated from the database. What I'm trying to accomplish is to be able click on a row in the datatable and when it's selected, store an ID value contained in the datatable into an array for later use. If a particular row is unselected, the array would be searched, and the matching ID value would be removed. Here is what I have tried so far. It seems to work sporadically:
$('#businessTable tbody').on('click', 'tr', function () {
var data = BusinessFileTable.row({ selected: true }).data();
if ($(this).hasClass('selected') == false) {
FullBusinessRecordIDs.push(data.BusinessID);
} else {
var index = FullBusinessRecordIDs.indexOf(data.BusinessID);
if (index > -1) {
FullBusinessRecordIDs.splice(index, 1);
}
}
});
Any suggestions on what I can do to improve on it? Does anyone know of a sample out there?

I think you should use the select extension and rebuild FullBusinessRecordIDs on each select / deselect event :
var FullBusinessRecordIDs = [];
$('#example').on('select.dt deselect.dt', function() {
FullBusinessRecordIDs = [];
table.rows({ selected: true }).every(function() {
FullBusinessRecordIDs.push( this.data().BusinessID )
})
//how as demo string
$('#ids').val( FullBusinessRecordIDs.toString() )
})
demo -> http://jsfiddle.net/4rnsq28s/

Related

Isotope v2 Grid - Multiple Filters - Hide empty filters

My current isotope grid has two dropdown filters that sort the grid items. The first filter is menu type, and the second filter is drink type. Each menu type however does not contain all drink types so when some filter configurations are chosen, no results are showed, which is correct. But i would like to stop this from happening by when the user selects the first filter, the second filter hides the empty types.
Working Codepen of current filters: https://codepen.io/whitinggg/pen/zYGEaNb
This was my old filter code:
// Select Filters
jQuery(function ($) {
var $grid = $('.grid');
var $selects = $('div#filterGroup select').change(function() {
var selector = $selects.get().map(function(el) { // map the select elements ...
return $(el).val(); // ... to an array of values
}).join('') || '*'; // if joined array is empty-string, then default to a single '*'
$grid.isotope({
'filter': selector
});
return false;
});
$grid.imagesLoaded().progress( function() {
$grid.isotope('layout');
});
});
I have tried to change my code to the below from other links around the internet on this topic but havent had any luck getting it to work.
// Select Filters
jQuery(function ($) {
var $grid = $('.grid');
var $selects = $('div#filterGroup select').change(function() {
var selector = $selects.get().map(function(el) { // map the select elements ...
return $(el).val(); // ... to an array of values
}).join('') || '*'; // if joined array is empty-string, then default to a single '*'
$grid.isotope({
'filter': selector
});
return false;
});
//Hide Empty Filters
var DROP = $('div#filterGroup select option:not([data-filter=""])');
// list of all class in html
var strall = ''; $('.grid-item').each(function(el){ strall += $(this).attr('class') });
// remove select if not in strall.. TODO : needs improvement, this is kind a hack
DROP.each(function(el){
var nowfilter = $(this).attr('data-filter').replace('.', ''); // co_kenya
if( strall.indexOf( nowfilter ) == -1 ){
console.log( 'this one is missing ' + nowfilter );
$(this).remove();
}
});
$grid.imagesLoaded().progress( function() {
$grid.isotope('layout');
});
});
Is this possible? Any help much appreciated!
Working codepen
First, add an ID to each drop-down so that we can distinguish them.
<select id="menu-selector" class="filter option-set" data-filter-group="menu">
[...]
<select id="type-selector" class="filter option-set" data-filter-group="categories">
Then, for each drop-down, add a change listener. We'll look at the code for the menu drop-down change listener.
First, get the class filter from the selected drop-down:
$('#menu-selector').change(function() {
var selectedClass = $('#menu-selector option:selected').attr('value');
Then we're going to select all of the grid items matching that type, to see what other classes they have. These other classes will be the available types
var availableTypes = $(`.grid-item${selectedClass}`)
.toArray()
.flatMap(div => Array.from(div.classList.values())) //get all of the classes
.filter(i => !['grid-item', selectedClass.substring(1)].includes(i)); //eliminate useless ones
Last, toggle the disabled property on the other drop-down, enabling only those that are available.
$('#type-selector option')
.each( (i,el) => $(el).prop('disabled', el.value != "" && !availableTypes.includes(el.value.substring(1))));
That should do it. The change handler for the type drop-down is the same but references the opposite drop-down. Check the codepen for details.

JSTree with Datatables

I have two columns on a page, with a checkbox jstree on the left and a table using datatables on the right. The table rows and tree are all loaded at startup.
I would like to show a row when the node is selected on the tree and hide the row when its unchecked and I'm using a class for this. I am having problems with looping though all the rows in a datatables and setting a class, so I can filter it. This is the code I'm using below, but its not working. I can't get any id for the table row.
table.rows().iterator( 'row', function ( context, index ) {
var tableNode = $(this.row(index).node());
tableNode.removeClass('VisibleRow').removeClass('HiddenRow').addClass('HiddenRow');
var id = tableNode.id;
var treeNode = data.instance.get_node(id);
if(treeNode != undefined){
var currentId = '#row-' + node.id;
var rowInTable = table.row(currentId).node();
$(rowInTable).removeClass("HiddenRow");
$(rowInTable).addClass("VisibleRow");
}
});
Let me know if there are better ways to do this.
I believe you can do it with the snippet below. The rows iteration is jQuery based, there is no DataTables-specific logic there.
Also check demo - Fiddle Demo
var $tableRows = $('#yourTableId').find('tr');
$('#yourTreeContainer').on('select_node.jstree', function(e, data) {
$tableRows.each(function() {
if (this.id === '#row-' + data.node.id) {
$(this).removeClass('HiddenRow');
} else {
$(this).addClass('HiddenRow');
}
});
});
I created same with some changes and it works fine, but even with hidden row I don't want datatable showing empty pages. Any advice, please?
this my code
$('#jstree')
.jstree({
core: {
data: treeData
},
checkbox: {
three_state : false, // to avoid that fact that checking a node also check others
whole_node : false, // to avoid checking the box just clicking the node
tie_selection : false // for checking without selecting and selecting without checking
},
"plugins" : ["checkbox","conditionalselect"]
})
.on("check_node.jstree uncheck_node.jstree", function(e, data) {
$tableRows.each(function(){
//$(this).addClass('HiddenRow'); //should not be there
if( this.id === data.node.id ) {
if(data.node.state.checked ){
//alert("removeClass");
$(this).removeClass('HiddenRow');
}else{
//alert("addClass");
$(this).addClass('HiddenRow');
};
}else{
}
})
})
This is the link http://jsfiddle.net/cf7tata9/56/#&togetherjs=jqPTfx3gpk

Delete a row of Bootstrap Table

Excuse me, now I am using this Bootstrap table. I don't know how to remove a row in the table, I have seen one similar example in the documentation, but I don't really understand what it means. Especially I don't know what {field: 'id', values: ids} means. The user experience I want to achieve is click button in any row that I want to remove, then that row will be removed.
Get defined bootstrap table as variable.
let table = $('#table');
Detect click event with remove button
$(document).on('click', '.removeRowButton', function() {
In bootstrap-table elements in rows have data-index.
Next row getting clicked row index
let rowid = $(this).closest('tr').data('index');
Built in function for removing rows
table.bootstrapTable('remove', {
field: '$index',
values: [rowid]
});
let table = $('#table');
$(document).on('click', '.removeRowButton', function() {
let rowid = $(this).closest('tr').data('index');
table.bootstrapTable('remove', {
field: '$index',
values: [rowid]
});
});
$(document).on('click', 'button.removebutton', function () { // <-- changes
$(this).closest('tr').remove();
return false;
});

toggle row with specific attribute in jquery datatable on click

I'm new to jquery datatable.
What I'm trying to achieve is, to toggle(hide/show) the row of datatable which is having attribute named status_id with value 9 to 13 on button click.
I have tried this for only number 9, but it's not working.
var dTable = $('#tbl_taskList').DataTable();
$(document).on('click', '.hide-tasks', function (e) {
e.preventDefault();
var row = dTable.row($(this).attr('status_id'));
if(row === '9') {
dTable.row().hide();
}
});
There is no hide() feature for rows. Basically is what you are trying to do a specialized filter, so you could create a custom filter to achieve what you want. Here is an example of a toggleable filter which hide or shows <tr>'s with status_id 9 or 13 :
$('#hide-tasks').on('click', function (e) {
//is the checkbox checked?
if ($(this).is(':checked')) {
//add filter
$.fn.dataTable.ext.search.push(function( settings, data, dataIndex ) {
//always go through the API when working with dataTables!
var status_id = parseInt(table.row(dataIndex).nodes().to$().attr('status_id'))
return !~[9,13].indexOf(status_id)
})
} else {
//reset filter
$.fn.dataTable.ext.search.pop()
}
//update table
table.draw()
})
demo -> http://jsfiddle.net/k1cz6rma/
Datatables docs says table.row hasn't hide fucntion but row().child() does.
var row = dTable.row(':eq('+$(this).attr('status_id')+')');
row.child().hide(); // hides
row.child().show(); // shows
checkout this page
row().child().hide()

How to get the selected check boxes in Kendo Mobile

I'm new to kendo I have a list populated from a data source (with template : Each list item has mobile switch in it).I need to get all the id's of selected mobile switches when I clicked on a single button. Can anyone let me know how to do that in kendo ?
Cheers,
Chinthaka
I solved that Using following code (Only Active Items checked items)
var checkedWorkCentersIds = new Array();
$('#workcenters :checkbox:checked').map(function () {
if (this.checked == true) {
checkedWorkCentersIds.push(this.id);
}
});
Without the code it is hard to give an exact answer, but you should be able to just loop over the data items in the array and find the ones that are selected.
For example:
var dataSource = new kendo.data.DataSource( ... );
function getSelected() {
return $.grep(dataSource.view(), function (item) {
return item.selected;
});
}
Assuming the switches/checkboxes are bound to the "selected" property.
In response to your comment, you can get the selected checkbox element IDs with jQuery:
$("#workcenters :checkbox:checked").map(function (index, checkbox) {
return $(checkbox).attr("id");
});

Categories

Resources