How to eliminate the empty rows from the jTable jQuery? - javascript

I have two jTables in my web page, which loads data from a database. The first jTable fetches the data directly from the database and the second table loads its data according to the selected data in the first table.
The problem now I am facing is, in-case if there are no data to be fetched for the second table, from the particular selected row, the rows are displaying empty.
For example, I have selected a data in the table 1, but since there is no data related to the selected data, the second table is displaying empty rows.
How to hide or not to fetch if the rows were completely empty at the same time if the row has even a single entry I wanted to display that row.
I am using python in the back end to fetch the data. So, do I need to make changes in my python code or do I need to make a change in the front end jQuery or CSS.
I have tried to use the jQuery, it is not working as expected.
My first jTable code is:
$('#SelectCode').jtable({
selecting: true,
paging: true,
actions: {
listAction:// my back end connection here
},
fields: {
codes: {
title: 'Code',
},
name:{
title: 'Name',
},
},
selectionChanged: function () {
var $selectedRows = $('#SelectCode').jtable('selectedRows');
if ($selectedRows.length > 0) {
$selectedRows.each(function () {
var record = $(this).data('record');
Code = record.event_codes;
$('#System').jtable('load',{code:(SelectedCode)});
});
},
});
My second jTable code is:
$('#System').jtable({
selecting: true,
paging: true,
actions: {
listAction:// my back end connection here
},
fields: {
date:{
title:'Date',
},
Time:{
title:'Time'
},
},
});
So, can someone, please help me how can I achieve in eliminating the empty rows from the table.
Thanks,

I have achieved it by adding the following line of codes in my jTable fields:
display: function(data) {
if (data.record.date == null) {
$("#System tr").each(function() {
var cellText = $.trim($(this).text());
if (cellText.length == 0) {
$(this).hide();
}
});
}
return data.record.date;
},

Related

Adding to x-editable select source with button click

I have using BootstrapTable with X-editable. I have a select box, that I would like to update the source data with a button click. Ideally, I like to get the source from the column, push a value to it and reload it without changing any edits to that column by the user.
Full code:
http://jsfiddle.net/rp4nkb46/1/
relevant code:
$('#addoption').click(function () {
names.push({value: 5, text: 'Bob'})
$('#table').bootstrapTable('OnRefresh', {});
});
Use a function to return the names array rather than specifying the array directly in your table setup:
$(function () {
$('#table').bootstrapTable({
columns: [{field: 'Contact',
title: 'Contact',
editable: {
type: 'select',
source: function() { return names; }
}
}],
data: data
});
});
It seems that the X-Editable will bind a supplied array once upon creation of the control but will call the function each time.

Kendo UI Grid change row detail values from command function without detail collapse

I have a kendo grid with a detail template, which I wish to clear if the user clicks on the clear command in the parent row.
I managed to get this to work, but as soon as I set the value on the dataItem, the row detail collapses, which causes the user to loose his place.
function clearDetails(e) {
var dataItem = this.dataItem($(e.currentTarget).closest("tr"));
dataItem.set("City",""); // causes row detail collapse
}
$(document).ready(function () {
$("#grid").kendoGrid({
dataSource: {
type: "odata",
transport: {
read: "https://demos.telerik.com/kendo-ui/service/Northwind.svc/Customers"
},
},
columns: [{
field: "ContactName",
title: "Contact Name",
width: 240
}, {
field: "Country",
width: 150
}, { command: { text: "Clear", click: clearDetails }, title: " ", width: "180px" }],
detailTemplate: kendo.template($("#myRowDetailTemplate").html())
})
});
Working example:
https://jsbin.com/xuwakol/edit?html,js,output
Is there a way I can still clear the values in the row detail, without it collapsing.
I had the same issue I got around it by using the dataBinding function within the kendo grid.
Basically it checks for an item change event and will cancel the default action to close the grid. This allowed me to continue to use the set method.
Example:
$("#grid").kendoGrid({
dataBinding: function (e) {
if (e.action == "itemchange") {
e.preventDefault();
}
},
});
}
I managed to get this right by not using the set method on the dataItem. http://docs.telerik.com/kendo-ui/api/javascript/data/observableobject#methods-set
I just changed the value on the dataItem, dataItem.City =""; and with the help of jquery selectors cleared the value of the textarea.
function clearDetails(e) {
var dataItem = this.dataItem($(e.currentTarget).closest("tr"));
dataItem.City ="";
$(e.currentTarget).closest(".k-master-row").next().find("textarea[name='City']").val("");
}

rows not saving in pagination for jquery datatables table with multiple row selection

I was able to successfully implement Datatables using the jQuery library. The problem is that when i click on page 2 in the pagination area it acts fine however when I go back to page 1 the records i selected are no longer selected.
Here is what it's supposed to do: datatables select row example
I updated my datatables to version: 1.10.15
Here is my call to handle the click event:
$("#datatable_users tbody").on("click","tr",function(){$(this).toggleClass("selected");});
Here is my code for creating the DataTable:
$("#datatable_'.$ref.'").dataTable({
"iDisplayLength": '.$itemlimit.',
"language": {
"url": "http://cdn.datatables.net/plug-ins/1.10.12/i18n/English.json"
},
"processing": true,
"serverSide": true,
"ajax": { // define ajax settings
"url": \''.Pluto::registry('web_base_uri').'service/datatable?req=1&ref='.$ref.'\',
"data": function(data) {
var datafilter= $("form#JqueryDataTableFormFilter_'.$ref.'").serializeControls();
$.each(datafilter, function(key, value) {
data[key] = value;
});
//console.log(datafilter);
}
},
"orderCellsTop": true,
"dom": "Bfrtip",
buttons: [
{
"text": "'.$search_label.'",
"className":"btn btn-default BtnjQueryDataTableFilter",
"action": function ( e, dt, node, config ) {
dt.ajax.reload();
}
}
]
});
As in server side processing the DataTable gets redrawn when you paginate so you need to keep track of what all was selected before clicking the next page and manually highlight the selected rows after each page click.
Here's an exact same working example featured on their website.
https://datatables.net/examples/server_side/select_rows.html
Let me know if you have any questions.

Get the number of rows from a remote csv using Papa Parse in Javascript

I have the following function that reads data from a remote csv file and does some processing on it before displaying it on a datatable.
function loadGrid()
{
link='{{ url("thecsvfile") }}/'+$('#class-id').val();
Papa.parse(link, {
download: true,withCredentials: true,header:true,
step: function(results, parser) {
//.... process the data row by row
cleanDataForGrid(results.data);
},
complete:function()
{
table =$('#the-grid').DataTable({
responsive: true,
destroy: true,
'bProcessing': true,
paging: false,
searching: false,
info:false,
scrollCollapse:true,
'columnDefs': [{
'targets': 0,
'searchable':false,
'orderable':false,
'width':'1%',
'className': 'dt-body-center',
'render': function (data, type, full, meta){
return '<input type="checkbox" class="the_check">';
},
}],
});
updateDownloaded();
}
});
}
It currently works well, the problem is that when the CSV file has many rows, it takes a long time to load and at times the browser hangs or crashes.
Is there a way we can get the number of rows first, if the file has more than X rows avoid the download completely?
if I could get such an implementation where only the row count is returned.
function getRows()
{
var rowcount= Papa.parse(link, {download: false});
if(rowcount<50001) loadGrid();
}
Is it possible to have such an implementation?
It is perfectly possible to query a server-side program which will handle your needs : returns the number of rows of a CSV file.
Example: http://www.yoursite.com/handlers/csv/count?file=thecsvfile
You can initialize the view which the returned value in javascript code.
With php and the zend framework, you can inject the returned value with the viewmodel, and display itself inside your view.
<script type="text/javascript">
<!--
var maxcsvfileSize = 50001;
var thecsvfileSize = <?php echo $this->thecsvfileSize; ?>;
function loadGrid(thecsvfileSize){
// test the length of thecsvfile and do the job you need.
if (thecsvfileSize < maxcsvfileSize) {
// do the job
}
}
//-->
</script>
[EDIT]
Looking a bit on Papi documentation, you will have the right to use stream to handle big files :
Papa.parse("http://example.com/big.csv", {
download: true,
step: function(row) {
console.log("Row:", row.data);
},
complete: function() {
console.log("All done!");
}
});
...which is done relatively easily and is responding at 100 percent to your question and needs.

jQGrid celledit in JSON data shows URL Not set alert

I need to load a JSON from server and i want to enable a user to click and edit the value.
But when they edit, it should not call server. i mean i am not going to update immediately. So i dont want editurl. So i tried
'ClientArray' But still it shows Url is not set alert box. But i need
all the edited values when the user click Add Commented Items button this button will fire AddSelectedItemsToSummary() to save those in server
MVC HTML Script
<div>
<table id="persons-summary-grid"></table>
<input type="hidden" id="hdn-deptsk" value="2"/>
<button id="AddSelectedItems" onclick="AddSelectedItemsToSummary();" />
</div>
$(document).ready(function(){
showSummaryGrid(); //When the page loads it loads the persons for Dept
});
JSON Data
{"total":2,"page":1,"records":2,
"rows":[{"PersonSK":1,"Type":"Contract","Attribute":"Organization
Activity","Comment":"Good and helping og"},
{"PersonSK":2,"Type":"Permanant","Attribute":"Team Management",
"Comment":"Need to improve leadership skill"}
]}
jQGRID code
var localSummaryArray;
function showSummaryGrid(){
var summaryGrid = $("#persons-summary-grid");
// doing this because it is not firing second time using .trigger('reloadGrid')
summaryGrid.jqGrid('GridUnload');
var deptSk = $('#hdn-deptsk').val();
summaryGrid.jqGrid({
url: '/dept/GetPersonSummary',
datatype: "json",
mtype: "POST",
postData: { deptSK: deptSk },
colNames: [
'SK', 'Type', 'Field Name', 'Comments'],
colModel: [
{ name: 'PersonSK', index: 'PersonSK', hidden: true },
{ name: 'Type', index: 'Type', width: 100 },
{ name: 'Attribute', index: 'Attribute', width: 150 },
{ name: 'Comment', index: 'Comment', editable: true,
edittype: 'textarea', width: 200 }
],
cellEdit: true,
cellsubmit: 'clientArray',
editurl: 'clientArray',
rowNum: 1000,
rowList: [],
pgbuttons: false,
pgtext: null,
viewrecords: false,
emptyrecords: "No records to view",
gridview: true,
caption: 'dept person Summary',
height: '250',
jsonReader: {
repeatitems: false
},
loadComplete: function (data) {
localSummaryArray= data;
summaryGrid.setGridParam({ datatype: 'local' });
summaryGrid.setGridParam({ data: localSummaryArray});
}
});
)
Button click function
function AddSelectedItemsToSummary() {
//get all the items that has comments
//entered using cell edit and save only those.
// I need to prepare the array of items and send it to MVC controller method
// Also need to reload summary grid
}
Could any one help on this? why i am getting that URL is not set error?
EDIT:
This code is working after loadComplete changes. Before it was showing
No URL Set alert
I don't understand the problem with cell editing which you describe. Moreover you wrote "i need the edited value when the user click + icon in a row". Where is the "+" icon? Do you mean "trash.gif" icon? If you want to use cell editing, how you imagine it in case of clicking on the icon on the row? Which cell should start be editing on clicking "trash.gif" icon? You can start editing some other cell as the cell with "trash.gif" icon ising editCell method, but I don't think that it would be comfortable for the user because for the users point of view he will start editing of one cell on clicking of another cell. It seems me uncomfortable. Probably you want implement inline editing?
One clear error in your code is usage of showSummaryGrid inside of RemoveFromSummary. The function RemoveFromSummary create jqGrid and not just fill it. So one should call it only once. To refresh the body of the grid you should call $("#persons-summary-grid").trigger("refreshGrid"); instead. Instead of usage postData: { deptSK: deptSk } you should use
postData: { deptSK: function () { return $('#hdn-deptsk').val(); } }
In the case triggering of refreshGrid would be enough and it will send to the server the current value from the '#hdn-deptsk'. See the answer for more information.
UPDATED: I couldn't reproduce the problem which you described, but I prepared the demo which do what you need (if I understand your requirements correctly). The most important part of the code which you probably need you will find below
$("#AddSelectedItems").click(function () {
var savedRow = summaryGrid.jqGrid("getGridParam", "savedRow"),
$editedRows,
modifications = [];
if (savedRow && savedRow.length > 0) {
// save currently editing row if any exist
summaryGrid.jqGrid("saveCell", savedRow[0].id, savedRow[0].ic);
}
// now we find all rows where cells are edited
summaryGrid.find("tr.jqgrow:has(td.dirty-cell)").each(function () {
var id = this.id;
modifications.push({
PersonSK: id,
Comment: $(summaryGrid[0].rows[id].cells[2]).text() // 2 - column name of the column "Comment"
});
});
// here you can send modifications per ajax to the server and call
// reloadGrid inside of success callback of the ajax call
// we simulate it by usage alert
alert(JSON.stringify(modifications));
summaryGrid.jqGrid("setGridParam", {datatype: "json"}).trigger("reloadGrid");
});

Categories