Add href hyperlink to row or field in datatable - javascript

I've seen a lot of questions about this, however I cannot seem to get it working.
I have a datatable but I cannot get it to work. I use python-flask with bootstrap and I change a pandas dataframe to a html table with to_html().
<table width="100%" class="table table-striped table-bordered table-hover dataTable" id="dataTables-example"><thead>
<tr style="text-align: right;">
<th>id</th>
<th>user</th>
<th>status</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>1</td>
<td>1</td>
</tr>
<tr>
<td>2</td>
<td>1</td>
<td>1</td>
</tr>
</tbody>
</table>
and at the bottom of the body I have:
<script>
$(document).ready(function() {
$('#dataTables-example').DataTable({
"bDestroy": true,
"deferRender": true,
"columns": [
{ "data": "id" },
{
"data": "weblink",
"render" : function(data, type, row, meta){
if(type === 'display'){
return $('<a>')
.attr('href', data)
.text(data)
.wrap('<div></div>')
.parent()
.html();
} else {
return data;
}
}
}
]
});
});
</script>
I've looked at a lot of awnsers however they all contain the data as json in the javascript while my data is already in the html.

Use columnDefs when you have a DOM <table> and only need to target one or few columns :
$('#dataTables-example').DataTable({
destroy: true,
deferRender: true,
columnDefs: [{
targets: 0, //<-- index of column that should be rendered as link
render : function(data, type, row, meta){
if (type === 'display'){
return $('<a>')
.attr('href', data)
.text(data)
.wrap('<div></div>')
.parent()
.html();
} else {
return data;
}
}
}]
})
It works here -> http://jsfiddle.net/j9ez0sbj/

You have 3 columns in your html table but only define 2 columns in your initialization.
From datatables documentation for the columns initialization option:
Note that if you use columns to define your columns, you must have an entry in the array for every single column that you have in your table (these can be null if you don't wish to specify any options).
Depending on what your intent is, at the very least you need to add a definition for the third column, so something like this:
"columns": [
{ "data": "id" },
{
"data": "weblink",
"render" : function(data, type, row, meta){
if(type === 'display'){
return $('<a>')
.attr('href', data)
.text(data)
.wrap('<div></div>')
.parent()
.html();
} else {
return data;
}
}
},
{ "data": "status" } // Third column definition added
]

Related

extracting values from rows to use in a URL

I have generated a data table using the Datatables jquery plugin. The table is populated with JSON.
I want to extract cell values when I make a selection to use in a URL but I can't get it to work.
#I'm using django
import json
#my list
users = [[1,26,'John','Smith'],[2,33,'Dave','Johnson'],[1,22,'Aaron','Jones']]
#my json
user_json = json.dumps(users)
<table class="table table-striped- table-bordered table-hover table-checkable" id="user-table">
<thead>
<tr>
<th>Age</th>
<th>Record ID</th>
<th>First Name</th>
<th>Last Name</th>
<th>Actions</th>
</tr>
</thead>
</table>
<script type="text/javascript">
var userData = {{user_json|safe}};
</script>
var SourceHtml = function() {
var dataJSONArray = userData;
var initTable1 = function() {
var table = $('#user-table');
// begin table
table.DataTable({
responsive: true,
data: dataJSONArray,
columnDefs: [
{
targets: -1,
title: 'Actions',
orderable: false,
render: function(data, type, full, meta) {
//this is where I need help. I need for each a-tag to link to a django url pattern such as href="{% url 'users:select-user' id=id_value %}"
return '<i class="la la-edit"></i>';
},
},
],
});
};
return {
//main function to initiate the module
init: function() {
initTable1();
}
};
}();
jQuery(document).ready(function() {
SourceHtml.init();
});
I need a href link to a django url pattern such as href="{% url 'users:select-user' id=id_value %}" in each a tag. however, I can't get the values from the cells.
Datatables columns.render option can be used to access full data source of current row.
By using columns.render as function type, we can use third (3)
parameter to access another column index form same row of data
source.
var userData = [[1,26,'John','Smith'],[2,33,'Dave','Johnson'],[1,22,'Aaron','Jones']];
$('#example').dataTable( {
"columnDefs": [ {
"targets": -1,
"data": null,
"title": 'Actions',
"render": function ( data, type, row, meta ) {
return 'Download';
}
} ]
} );

How to display json array coming from url through ajax in angularjs

I have a json array coming from a url:
http://blahblahblah.com/company/all, like this:
in angularjs controller, i have something like this:
$('#example-1').DataTable({
"ajax" : 'http://blahblahblah.com/company/all',
"columns": [
{"data": "companyId"},
{.....}, // I can't assign "data" name to array because it is already unnamed.
]
});
Traversing in html table_id example-1
<table id="example-1" class="display" cellspacing="0" width="100%">
<thead>
<tr>
<th>Company</th>
<th>Legal Name</th>
<th>DBA Name</th>
<th>Formation</th>
</tr>
</thead>
<tfoot>
<tr>
<th>Company</th>
<th>Legal Name</th>
<th>DBA Name</th>
<th>Formation</th>
</tr>
</tfoot>
Output:
So, my question is how do I identify the column names from above UNNAMED JSON ARRAY mentioned on top of the question, and display it in html table. Waiting for your kind response.
I am thinking to do something like this
$(document).ready(function() {
$('#example').DataTable( {
"ajax": "http://blahblahblah.com/company/all",
"columns": [
{ "data": "companyId" },
{ "data": "legalName" },
{ "data": "dbaName" },
{ "data": "formation"}
]
} );
} );
you need to add more information to the datatable while intializing what are the keys to be shown. form more details check datatable objects
I was unable to identify the correct syntax of identifying and using the column names in my JSON array, which I did like this, and solved my problem. So now the data is displayed fine in my table, this way:
$.getJSON('http://blahblahblah/company/all', function(data) {
$('#companies').DataTable({
"aaData": data,
"aoColumns": [
{"mDataProp":"companyId"},
{"mDataProp":"legalName"},
{"mDataProp":"dbaName"},
{"mDataProp":"formation"}
]
});
});
I also added hyperlink to companyId like this:
$.getJSON('http://blahblahblah/company/all', function(data) {
var companyId = null;
$('#companies').DataTable({
"aaData": data,
"aoColumns": [
{"mDataProp":"companyId", "render": function(data, type, row, meta) {
if( type==='display' ) {
companyId = data;
data = '' + data + '';
}
return data;
}},
{"mDataProp":"legalName"},
{"mDataProp":"dbaName"},
{"mDataProp":"formation"}
]
});
});
I am thankful to all of you for helping me grab the track.
Thanks.
Actual way to do this is to use ng-repeat in the data array. And for the data fetch, use an angular service with a promise.
In the Controller
var self = this;// this is the controller which is aliased as ctrl at routing
var theData = yourService.FetchData(params).then(function(data){
self.tableData = data; // not going for the exact implementation.
},function(err){
manageError(err);// manage your errors here.
}));
In the HTML
<table id="example-1" class="display" cellspacing="0" width="100%">
<thead>
<tr>
<th>Company</th>
<th>Legal Name</th>
<th>DBA Name</th>
<th>Formation</th>
</tr>
</thead>
<tr ng-repeat="var item in ctrl.tableData ">
<td>{{item.companyId}}</td>
<td>{{item.legalName}}</td>
<td>{{item.dbaName}}</td>
<td>{{item.formation}}</td>
</tr>
</table>

Jquery find a row in unselected datatable by value in td

Is there an efficient jQuery way in a "legacy" datatable to find a td containing my search value and then crawl up to the row tr?
I can use $('#modalTable tbody').dataTable()[0].rows to get all rows and then loop through all rows but would prefer a more efficient method if there is one.
Here is a screen capture of what I have tried based on information I found on similar questions:
I've expanded all the values in the Watches. This screen capture is amazingly small! You may need to save the image to see it better.
One thing that may be important is that this table is created in a popup. I want to find the rows while the popup is opening but the data is already loaded into the table. Here is the code:
// Intitializes the select building table with new data
// and resets the DOM every time the "Add" button is clicked.
initSelectableBuildingTable = function () {
//If table exists destroy and reinitialize
var is_table = isDataTable(jQueryVar.jSelectableBuildingTable)
if (is_table) {
resetDatatable(jQueryVar.jSelectableBuildingTable);
}
jQueryVar.jSelectableBuildingTable.dataTable({
"bPaginate": false,
"bProcessing": true,
"bAutoWidth": true,
"aoColumns": [
{
"mDataProp": "Id", "bSortable": false, "mRender": function (data, type, row) {
var sHtml = '<input type="button" class="button small addSelectedBuilding" value="Add" data-id="' + row.AssetId + '"/>'
return sHtml;
},
"bUseRendered": false,
"sDefaultContent": ""
},
{ "mDataProp": "AssetName", "bSortable": true },
{ "mDataProp": "SqFoot", "bSortable": true },
{ "mDataProp": "Uid", "bSortable": true },
{ "mDataProp": "Category", "bSortable": true },
{ "mDataProp": "Location", "bSortable": true }
],
"aoColumnDefs": [
{ "mDataProp": null, "sDefaultContent": " ", "aTargets": [-1] }
],
"sDom": '<"top">rt<"bottom"><"clear">',
"oLanguage": {
"sEmptyTable": "No Meters found."
},
"sAjaxSource": $.baseURL("api/service/getassetsbyids"),
"fnServerData": function (sSource, aoData, fnCallback) {
var ids = stateMap.selectedSiteIds.toString();
var oData = { "ids": ids, "type": stateMap.selectedAssetType.toLowerCase() };
$.ajax({
url: sSource, // Do not add the base to this. It should already be present
type: "GET",
data: oData,
dataType: "json",
success: fnCallback,
complete: function () {
if (Info.model.getItemCount() > 0) {
disableAddButtonForSelectedItems();
}
}
});
}
});
}
Maybe there is some awesome cool thing that will allow me to find the the dt value and crawl up to the row.
You can use the :contains selector in jquery:
$('td:contains(Another option)').parent('tr').css('background', 'red');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr>
<td>This is my text</td>
<td>Some other text</td>
</tr>
<tr>
<td>Another option</td>
<td>This is what I'm looking for</td>
</tr>
<tr>
<td>And some row</td>
<td>Note this Another option row</td>
</tr>
</table>
But Note as in my example, it's not an exact match. It's "contains" match.
If you want to change it to exact match you can use something like that:
var content_to_search = 'Another option'
$(`td:contains(${content_to_search})`).each(function() {
if ($(this).text() == content_to_search) {
$(this).parent('tr').css('background', 'red');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr>
<td>This is my text</td>
<td>Some other text</td>
</tr>
<tr>
<td>Another option</td>
<td>This is what I'm looking for</td>
</tr>
<tr>
<td>And some row</td>
<td>Note this Another option row</td>
</tr>
</table>
OK. I was close. You can click on the image to see just how close. Technically, Dekel's answer is the correct answer, so I'm going to give the points to that answer here. But I'm posting this answer just-in-case someone else finds themselves as confused as I was.
I was trying to get the row and then perform whatever action I wanted on it (WRONG!), which may still be possible but I found the better way that I was looking for.
This is the code that does what I wanted:
var ids = []; // These will come from user selection
ids.forEach(function (id)
jQueryVar.jBuildingTable.find('tr input[data-id="' + id + '"]') // Find row
.prop("disabled", true).addClass('secondary'); // perform action
Happy coding!

how to populate jquery datatables with json?

I am using jquery datatable in my application, plugin link https://datatables.net/
I want to populate my datatable with JSON, but I am failed.here is my code.
HTML:
<table id="example" class="display" width="100%" cellspacing="0">
<thead>
<tr>
<th>id</th>
<th>Name</th>
<th>Code</th>
<th>Description</th>
<th>isActive</th>
</tr>
</thead>
<tfoot>
<tr>
<th>id</th>
<th>Name</th>
<th>Code</th>
<th>Description</th>
<th>isActive</th>
</tr>
</tfoot>
<tbody>
</tbody>
</table>
JS:
$(document).ready(function() {
console.log("hi ready");
$('#example').DataTable({
retrieve: true,
ajax: {
url: '/ProductLicensingApplication/feature/list',
dataSrc: ''
},
"columns": [
{ "data": "id" },
{ "data": "name" },
{ "data": "code" },
{ "data": "description" },
{ "data": "isActive" }
]
});
} );
my json
but I am not able to populate data into the table as the table shows no data available in the table..you can see in the image
please tell me what is the problem in my code...
As written in documentation. The ajax.dataSrc option is used to tell DataTables where the data array is in the JSON structure. An empty string is a special case which tells DataTables to expect an array.
In your case JSON is an object and you should set dataSrc : 'features'
Ahmad,
Either set dataSrc : 'features' or if possible rename the attribute name 'features' to 'data' in the response data.

Jquery Datatables How to get column Id in render function

I'm trying to create a reference into the row cell.
This is my code:
<table class="table table-striped table-bordered table-hover little_margin_table" id="data-table" width="100%">
<thead>
<th>First Name</th>
<th>Email</th>
<th>Password</th>
</thead>
<tbody>
#foreach (var item in Model.Items)
{
<tr id="#item.Id">
<td>#item.FirstName</td>
<td>#item.Email</td>
<td>#item.Password</td>
</tr>
}
</tbody>
</table>
Javascript code:
$(document).ready(function () {
$('#data-table').dataTable({
bFilter: false,
aoColumnDefs: [
{
bSortable: false,
aTargets: [1, 2],
},
{
"targets": 0,
"render": function (data, type, full, meta) {
return '<a href = "#(Url.Action("IndexPage", "Company"))/' + ROWID '</a>';
}
},
]
})
Here I am assuming the row Id :
<tr id="#item.Id">
How can get it to into the function render:
"render": function (data, type, full, meta) {
return '<a href = "#(Url.Action("IndexPage", "Company"))/' + ROWID '</a>';
Help, please.
You could add a extra column to your table:
<td>#item.FirstName</td>
<td>#item.Email</td>
<td>#item.Password</td>
<td>#item.Id</td>
Which is set to hidden in the datatables init code:
'bVisible': false
When you use render you can now get the Id value from full:
"render": function (data, type, full, meta) {
return '<a href = "#(Url.Action("IndexPage", "Company"))/' + full[3] + '</a>';
You could use a delegated event handler to add the id to the link when it is clicked :
$("#data-table").on("click", "td:eq(0) a", function(e) {
this.href+=$(this).closest('tr').attr('id');
})
And forget about adding ROWID to the href in the render callback. The table is generated serverside and your Model.items is never passed to the client as data, so I cannot see any other workaround.

Categories

Resources