Quantcast
Channel: DataTables 1.9 — DataTables forums
Viewing all 1816 articles
Browse latest View live

Dynamically Add new column for Edit rows in data table asp.net c# 4.5

$
0
0
Hello,

I am newer in jquery datatable. I have bind a datatable using jqyery datatable. Now i want edit link on each row, I have used below code

 <table id="grid" class="display">
                <thead>
                    <tr>
                        <th>Actions</th>
                        <th>Name</th>
                        <th>IsActive</th>
                        <th>CreatedOn</th>

                    </tr>
                </thead>
                <tbody>
                    <tr>
                        <td></td>
                        <td></td>
                        <td></td>
                        <td></td>
                    </tr>
                </tbody>
            </table>


<script type="text/javascript">
        $(document).ready(function () {
            var grid = $('#grid').dataTable({
                "bProcessing": true,
                "sPaginationType": "full_numbers",
                "bServerSide": true,
                "sAjaxSource": "../AdminServices.asmx/GetCategories",
                "fnServerData": function (sSource, aoData, fnCallback) {

                    var jsonAOData = JSON.stringify(aoData);

                    $.ajax({
                        //dataType: 'json', 
                        contentType: "application/json; charset=utf-8",
                        type: "POST",
                        url: sSource,
                        data: "{jsonAOData : '" + jsonAOData + "'}",
                        success: function (msg) {
                            fnCallback(JSON.parse(msg.d));
                        },
                        error: function (XMLHttpRequest, textStatus, errorThrown) {
                            alert(XMLHttpRequest.status);
                            alert(XMLHttpRequest.responseText);

                        }
                    }


                    );
                },
                "aoColumnDefs": [
                   {
                       "fnRender": function (oObj) {
                           return "<a href='center.aspx?centerid=" + oObj.aData[0] + "'>Edit</a>";
                       },
                       "bSortable": false,
                       "aTargets": [0]
                   },
                   {
                       "sName": "Name",
                       "bSearchable": true,
                       "aTargets": [1]
                   },
                   {
                       "sName": "IsActive",
                       "bSearchable": true,
                       "bSortable": true,
                       "aTargets": [2]
                   },
                   {
                       "sName": "CreatedOn", "bSearchable": true,
                       "bSortable": true, "aTargets": [3]
                   }
                ]
                



            });

            grid.fnSetFilteringDelay(1000);
        });


    </script>

[WebMethod]
    [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
    public string GetCategories(string jsonAOData)
    {
        Enforce.That(string.IsNullOrEmpty(jsonAOData) == false,
                        "GetaData.GetTenants - jsonAOData can not be null");

        CategoriesBL categoryBL = new CategoriesBL();
        var jsonSerialiser = new JavaScriptSerializer();
        var json = categoryBL.GetAllCategory().AsQueryable();

        //var tenantRepository = new  ; 
        //var tenants = tenantRepository.AsQueryable();

        var dataTablePager = new DataTablePager<Category>(jsonAOData, json);
        var formattedList = dataTablePager.Filter();

        return JsonConvert.SerializeObject(formattedList);
    }

I am getting below response from web service

{"d":"{\"sEcho\":1,\"iTotalRecords\":8,\"iTotalDisplayRecords\":8,\"aaData\":[[\"1\",\"Beauty and Wellness\\r\\n\",\"True\",\"2/23/2014 11:44:42 AM\"],[\"2\",\"Leisure and Entertainment\\r\\n\",\"True\",\"2/23/2014 11:44:47 AM\"],[\"3\",\"Travel and Accommodation\\r\\n\",\"True\",\"2/23/2014 11:44:56 AM\"],[\"4\",\"Commerce\\r\\n\",\"True\",\"2/23/2014 11:45:02 AM\"],[\"5\",\"Services\\r\\n\",\"True\",\"2/23/2014 11:45:07 AM\"],[\"6\",\"Businesses\\r\\n\",\"False\",\"2/23/2014 11:45:11 AM\"],[\"7\",\"Health\\r\\n\",\"True\",\"2/23/2014 11:45:17 AM\"],[\"8\",\"Useful\\r\\n\",\"True\",\"2/23/2014 11:45:18 AM\"]],\"sColumns\":\"ID,,Name,,IsActive,,CreatedOn,\"}"}


Issue is like when i am binding with datatable, its generating wired result

It generates some thing like below
Actions	 	                 Name	        IsActive	                                        CreatedOn
Edit	               True	        undefined	Beauty and Wellness	                undefined
Edit	               True 	undefined       Leisure and Entertainment	        undefined
Edit	               True  	undefined	Travel and Accommodation	        undefined
Edit	               True	        undefined	Commerce	                                undefined
Edit	               True 	undefined	Services	                                        undefined
Edit                 False	undefined	Businesses	                                undefined
Edit	               True	        undefined	Health	                                        undefined
Edit	               True	        undefined	Useful	                                        undefined

Not sure why. Can you please help me at earliest?

Thanks,
Nik

Values right-align

$
0
0
Hi,

is it possible to show price quotations flush right in the DataTable?
The data shown are from a MySQL-Database and the datatype is double.

Thanks for your help!

Multi-column sort not working for second click

$
0
0
Hi Allan,

I used your code to sort programmatically on two columns but it sorts only the first time. It doesn't sort second time descending. Here's my code. Please help. Thank you.

I want the first column to always be sorted ascending regardless which other column is sorted on.

$(document).ready(function () {

var SortTable = $('#tblUploadHistory').dataTable();
SortTable.fnSortListener(document.getElementById('ValidatedDate'), 1);
$('#Overall').click(function () {
var ColumnSort = SortTable.fnSettings().aaSorting;
if (ColumnSort[0][0] != 2 || ColumnSort[0][1] == 'desc') {
SortTable.fnSort([[4, "asc"], [0, "asc"]]);
}
else {
SortTable.fnSort([[4, 'desc'], [0, 'asc']]);
}
});

});

function PopulateUploadDataTable(FacilityUploadItems) {

var Table = $('#tblUploadHistory').dataTable({
"sScrollY": "255px",
"bPaginate": false,
"bLengthChange": false,
"bFilter": false,
"bSort": true,
"bInfo": true,
"bAutoWidth": false,
"aaSorting": [[0, "desc"],
"aaData": FacilityUploadItems,
"aoColumns": [
{ "mDataProp": "Submitted Date", sClass: "tdData" },
{ "mDataProp": "Submitted By", sClass: "tdData" },
{ "mDataProp": "Validated Date", sClass: "tdData",
"mRender": function (data, type, full) {
return '<td>' + $.datepicker.formatDate('mm/dd/yy', new Date(data)) + '</td>';
}
},
{ "mDataProp": "Overall %", sClass: "tdData" },
{ "mDataProp": "Hourly +/-3%", sClass: "tdData" },
{ "mDataProp": "Category +/-3%", sClass: "tdData" },
{ "mDataProp": "CERTIFIED", sClass: "tdData" },
{ "mDataProp": "File Name", sClass: "tdData",
"mRender": function (data, type, full) {
return '<a href="TCIPdownload.aspx?name=' + data + '">' + data + '</a>';
}
}
,
{ "mDataProp": "Validated Date" }
],
"aoColumnDefs": [{ "bVisible": false, "aTargets": [8] },
{ "iDataSort": 8, "aTargets": [2]}],
"bDestroy": true

});

$('#tblUploadHistory').show();
$("#divUploads").show();

setTimeout(function () {
Table.css('width', '100%');
Table.fnAdjustColumnSizing();
}, 10);

}


<table id="tblUploadHistory" cellpadding="0" cellspacing="0" border="0" class="display">
<thead>
<tr>
<th id="thFacName" class="tdHeadingCenter" colspan="8">Facility Name</th>
</tr>
<tr>
<th class="tdSubHeading">Submitted Date</th>
<th class="tdSubHeading">Submitted By</th>
<th class="tdSubHeading" id="ValidatedDate">Validated Date</th>
<th class="tdSubHeading" id="Overall">Overall %</th>
<th class="tdSubHeading">Hourly +/- 3</th>
<th class="tdSubHeading">Category +/- 3%</th>
<th class="tdSubHeading">Certified</th>
<th class="tdSubHeading">File Uploaded</th>
<th class="tdSubHeading">SortValidatedDate</th>

</tr>
</thead>

Thank you very much for your help.

Best regards,

Ali

Datatable check/uncheck 'All'

$
0
0
Hi Allan,

Am using datatables in one of my projects. Am doing select All/None with the following code
$('#check_all').click( function() {
         $('input', oTable.fnGetNodes()).attr('checked', this.checked);
})
Say if I have 10 rows. Initially if I select few rows (say 4 and 5) then unselect it and then click on check All. Those 2 rows(4 and 5) are not checked. But when checked in source (Inspect element/firebug) check box says as checked.

Your help is appreciated.

Thanks,
Rizwan

Clear saved state by clearing local storage

$
0
0
Hi

My application uses tables with a whole bunch of columns. I'm using the fabulous ColVis plugin to hide and show the columns the user wants. Thanks to fnStateSave, I can very easily keep all filters and columns present after a page reload.

The problem is that if there's a filter present in one of the columns (I've got input boxes below each column) and that column is hidden, it's confusing for the user. The user sees a filtered table, but cannot see which column has been filtered.

My question is: I would like to implement a global table reset button, that clears the saved state of the current table only: filters, columns... the whole shabang. Ideally the button would be displayed in the same manner as the TableTools and ColVis buttons.

How would I go about implementing such a feature?

		"bStateSave": true,
		"fnStateSave": function (oSettings, oData) {
            localStorage.setItem( 'DataTables_'+window.location.pathname, JSON.stringify(oData) );
        },
        "fnStateLoad": function (oSettings) {
            return JSON.parse( localStorage.getItem('DataTables_'+window.location.pathname) );
        },		
		"fnStateLoadParams": function (oSettings, oData) {
			$(oData.aoSearchCols).each(function(index,value) {
				if(value.sSearch != '') {
					$("input.search_init[data-colno='" + index + "']").val(value.sSearch);
				}
			});
		}


Thanks in advance for your answer. And thank you for your great software! My client LOVES it!

cross domain ajax works but there's no data displayed in my table : (

$
0
0
https://datatables.net/release-datatables/examples/server_side/jsonp.html

The above setting works (below) - confirmed on the firebug, the JSON data is retrieved, but my issue is it's not shown on the table!!

Any clues why??

    $(document).ready(function() {
        $('#table_id').dataTable( {
                "bProcessing": true,
                "bServerSide": true,
				"sAjaxSource": "http://localhost:9001/api/gui/messages",
				"fnServerData": function( sUrl, aoData, fnCallback, oSettings ) {
			            oSettings.jqXHR = $.ajax( {
			                "url": sUrl,
			                "data": aoData,
			                "success": fnCallback,
			                "dataType": "jsonp",
			                "cache": false
			            } );
				},
                "bDeferRender": true,
                "aoColumns": [
						{ "mData": "busId", "bSortable": false },
						{ "mData": "sourceSystem", "bSortable": false },
						{ "mData": "receiveTime", "bSortable": false },
                                                ...
				     ],
                "sDom": "rtp",
                "sPaginationType": "full_numbers",
                "iDisplayLength": 20
            } );
        } );               



Just to verify things, if source data locally i.e. replace:
"sAjaxSource": "http://localhost:9001/api/gui/messages",
"fnServerData" ...

with something like:
"sAjaxSource": "resources/data.txt",

then all works!

I'm using DataTables 1.9.4

Thanks!

Row headers instead of column headers?

how i can put images in my data table from data base?


Sending and getting an Array using fnServerParams

$
0
0
I am having problems sending and getting data from an array using fnServerParams. Can some one please help?
Thanks my javascript code
function generateDataTable(subject, checkboxes) {

    
    var oTable = $('#datatable1').dataTable({
        "bProcessing": true,
        "bServerSide": true,
        "sAjaxSource": base_url() + '/' + 'ccreateexam/getQuestions',
        "fnServerParams": function(aoData) {
            aoData.push({"name": "subject", "value": subject});
            aoData.push({"name": "checkboxes[]", "value": checkboxes});
           
        },
        "bJQueryUI": true,
        "sPaginationType": "full_numbers",
        "iDisplayStart ": 20,
        "oLanguage": {
            //"sProcessing": "<img src='<?php echo base_url(); ?>assets/images/ajax-loader_dark.gif'>"
        },
        "fnInitComplete": function() {
            oTable.fnAdjustColumnSizing();
        },
        'fnServerData': function(sSource, aoData, fnCallback)
        {
           // alert(sSource);
            $.ajax
                    ({
                        'dataType': 'json',
                        'type': 'POST',
                        'url': sSource,
                        'data': aoData,
                        'success': fnCallback
                    });
        }
    });
}

And in my controller

public function getQuestions() {
        
        $subject = $this->input->post('subject');

        $checkboxes = $this->input->post('checkboxes');
       
        echo $this->mcreateexam->getQuestionsForSubjectLessons2($subject, $checkboxes);

    }

Thanks

First argument in fnFooterCallback is always null

$
0
0
I am using sDom to create the table.

When fnFooterCallback is called the first param is always null (in this case nFoot):

$('#example').dataTable( {
    "fnFooterCallback": function( nFoot, aData, iStart, iEnd, aiDisplay ) {
      nFoot.getElementsByTagName('th')[0].innerHTML = "Starting index is "+iStart;
    }
  } );

Multiple table with aoColumnDefs

$
0
0
Hi everyone,

I've got two tables on the same page which i initialize in the same times ($(document).ready).
I use these with tabbable (bootstrap 2.3.1) to switch from one to the other.
The first one haven't any problem, it is correctly initialized. But the second not. The column width isn't right.

Can you help me please?
Thanks

How to create new row at middle of the table

Find filter location

$
0
0
Ive implemented data tables in my application. I need to know if i change the display location for find text box. by default it is showing on the Left top side of table and need to move it to the right top. How can i do that. is it through css or another way?

Unable to add data in the middle of table and delete the last row

$
0
0
Hi,
I'm using DataTables 1.9 and I'm trying to add a row in the middle of the table. I have read other posts on this forum, where its said that I can use a hidden column as an index columns and then insert the new row at the appropiate index. This method works for me, but I was looking for a workaround as I do not want to change the indexes of the rows below the inserted row. Do you have a better method? My use case is just to show the added row as the first row.
Also, if I am trying to delete the last row of my table, using fnDeleteRow(), it gives an error saying 'cannot read property nTr of undefined'. This happens only if i pass the row to be deleted. If i pass the rowIndex, it works perfectly. Here's the fiddle for the same:
http://jsfiddle.net/NpT26/25/ - using rowData
http://jsfiddle.net/NpT26/22/ - using Index.
Can you explain me the cause of this error?

Thanks,
Pratik

Event based DT refresh via fnDestroy (then re-init) and fnDataTablesPipeline incompatiblity issue

$
0
0
Hi,

In my use-case I have various search criteria fields that are submitted to server side when user presses a button. DT need be refreshed for each submission..

The approach I'm using is to fnDestroy and re-init the entire DT post each form submission - would like to ratify if this is the correct approach? Ideally should just able to refresh the existing table anew, and tried using the fnAjaxReload, but couldn't get that to work.


Current approach:
    $(document).ready(function() {
    	var oTable;
    	$('#runQ').click( function() {
    		if(oTable)
    		{
    			oTable.fnDestroy();
    		}
       		var sData = $('input').serialize();
       		oTable = $('#table_id').dataTable( {
                "bProcessing": true,
                "bServerSide": true,
                "bDestroy": true,
                "sAjaxSource": "query.do?"+sData,
...

Issue:

I can't use the excellent pipelining plugin in DT, due to some built-in caching in that? My table data stay old/stale when I use this plugin, however, I'm keen to get that to work as my data size is quite big and therefore would like to bulk load data on each server side trip.

Any expert advice/comments on how to address this challenge?

Thanks in advance!

Table not rendered when using aaData with JS-Array

$
0
0
Hi,

I'm not seeing what I'm doing wrong here and probably I looked at the code for too long to see anything ;-/
I'd appreciate some help in fixing this...
Baiscally this all worked with a 'tradional table' - but rendering was far too slow with > 1.000 records. So it seemed like a good idea to put it the data into a JS-Array and have DT do all the work ;-) But I've done something wrong in the transition and get an empty table.

http://mbaas.de/aadata.htm
and http://debug.datatables.net/odivus

Thanks

Michael

ASPX VB get Selected Row

$
0
0
I've seen how to highlight a selected row on the examples here. But I don't know how to get the selected row in my VB code.

I need to be able to select a row and then work with it in my VB code. I'm used to get the value like this: "ByVal e As System.Web.UI.WebControls.GridViewCommandEventArgs" from a RowCommand

Can someone tell me how to do it with this jquery gridview?

Thanks!!

Regex with 'OR' condition doens't work in fnFilter

$
0
0
Hi Alan,

I used the DataTables Debug BookMarklet to upload my datatables and the debug code is 'olohos'.

My issue is, the OR operator '|' or even '||' with string values to filter a column doesn't work in my web application.

For example, if I have the code below

$('.search_init').keyup(function()
{
var asEscapedFilters = [];
asEscapedFilters[0] = $(this).val();
asEscapedFilters[1] = 'Y';
oTable.fnFilter(asEscapedFilters[0] | asEscapedFilters[1], $('#example tr.inputs input').index(this), true, false);
});

And input the string 'I' in the search area for the 'Order Active' column, it is supposed to return all the rows which contains either 'I' or 'Y' for the 'Order Active' column. Instead it returns zero rows.

If I use '||' instead of '|' like the below,

$('.search_init').keyup(function()
{
var asEscapedFilters = [];
asEscapedFilters[0] = $(this).val();
asEscapedFilters[1] = 'Y';
oTable.fnFilter(asEscapedFilters[0] || asEscapedFilters[1], $('#example tr.inputs input').index(this), true, false);
});

It returns the rows which have 'Y' for the 'Order Active' column, but not the rows with 'I'.

I have already spent a lot of time, looking at this issue, any useful suggestions to get this work is very much appreciated.

The processing is server side, does it requires it to take care of any additional syntax or settings for this?

Many thanks in advance,
Vaasugi.

reload data after clicking button

$
0
0
I load data by default like this

$('.datatable').dataTable({
        "sPaginationType": "bs_full",
        "bProcessing" : true,
        "sAjaxSource" : "loadusers.html",
        "sAjaxDataProp" : "test"
    });

My table on html page looks like this
<table class="datatable table table-striped table-bordered" id="usertable">
                     <thead>
                        <th>Name</th>
                        <th>Surname</th>
                        <th>Username</th>
                    </thead>
                    <tbody>
                    </tbody>
                </table>


Server answer looks like this
 return "{ \"test\": [ "
                + "[ \"name1\", \"surname1\", \"username1\"],"
                + "[ \"name2\", \"surname2\", \"username3\"],"
                + "[ \"name2\", \"surname2\", \"username3\"]"
                + "] }"; 


But how to load data by clicking button on the page? For example by clicking button
<button id="button1" class="btn btn-primary">Clicker</button>

fnAddData and column width

$
0
0
In short, I have an empty table defined in HTML. I've initialized my dataTable in javascript. My data is coming in from an ajax source, but needs to be manipulated prior to going into the dataTable, so a separate function handles data acquisition and manipulation, and stores the data for the table in an object. I then use fnAddData to push the data into the dataTable.

I need to constrain the width of one of the columns, and have the text not wrapped but truncated with ellipsis. Unfortunately, it appears that I can either wrap the text, or have an absurdly wide column, as using fnAddData appears to ignore any column width settings, both in the HTML table definition as well as in the dataTable initialization.

HTML -
	<table id='table-summaryreport'>
		<thead>
			<tr>
				<th><input type="checkbox" class="selectall"></th>
				<th>CourseID</th>
				<th width="150px">Title</th>
				<th>LoginName</th>
				<th>SourceID</th>
				<th>UserName</th>
				<th>Average Course Logins</th>
				<th>Average Link Interactions</th>
				<th>Average Page Interactions</th>
				<th>Average Forum Interactions</th>
				<th>Average Forum Posts</th>
				<th>Average Forum Replies</th>
				<th>Average Dropbox Interactions</th>
				<th>Average Assessment Interactions</th>
				<th>Average Total Points Earned</th>
				<th>Average Calculated Final Grade</th>
			</tr>
		</thead>
	</table>

dataTable initialization -
oSummaryTable = $('#table-summaryreport').dataTable( {
        'bPaginate': true,
        'bAutoWidth': false,
        'iDisplayLength': 20,
        'bFilter': false,
        'bSort': true,
        'sDom': '<"clear"><"top"iT>rt<"bottom"lp>',
        'aLengthMenu': [[20,10,50,-1], [20,10,50,'All']],
        'bProcessing': true,
        'oTableTools': {
                'aButtons': ['copy', 'csv']
            },
        'aoColumns' : [
            {'sClass': 'center',    //create an extra column to hold the checkboxes'
            'bSortable': false,     //disable sorting on this column
            'mData': 'course_id',   //grab the info from the course_id data
            'mRender': function(data,type,full){ //and build a checkbox with a value = <course_id>
                return '<input type="checkbox" name="graph" value="' + data + '">';}},
            {'mData' : 'course_id'},
            {'mData' : 'title',
                'sWidth' : '150px'},
            {'mData' : 'loginname', //hide this column in the summary table
                'bVisible':false},
            {'mData' : 'sourceid',  //hide this column in the summary table
                'bVisible':false},
            {'mData' : 'username',  //hide this column in the summary table
                'bVisible':false},
            {'mData' : 'Course Logins'},
            {'mData' : 'Link Interactions'},
            {'mData' : 'Page Interactions'},
            {'mData' : 'Forum Interactions'},
            {'mData' : 'Forum Posts'},
            {'mData' : 'Forum Replies'},
            {'mData' : 'Dropbox Interactions'},
            {'mData' : 'Assessment Interactions'},
            {'mData' : 'Total Points Earned'},
            {'mData' : 'Calculated Final Grade'}],
            'fnRowCallback':function(nRow, aData, iDisplayIndex, iDisplayIndexFull){  //after building each row, go back and update the cells
                $('td:eq(1)',nRow).attr('id', aData.course_id).attr('class','SARcourseid').attr('title','Click on the CourseID to view a detailed activity report.'); //define the id for the course_id cell = <course_id>
                $(':checkbox',nRow).attr('id', iDisplayIndexFull); //give the checkbox an ID corresponding with the row index
                $('td:eq(2)',nRow).attr('class','SARtitle'); //insert the class=SARtitle on the title cells
                return nRow;
            }
    });

Pushing data into the table -
 oSummaryTable.fnAddData(oAverages);
Viewing all 1816 articles
Browse latest View live


Latest Images