Get render value of datatable column instead of data value - javascript

I am getting my datatable data from ajax.
My table have name surname and status columns
I am getting status from database as 0 or 1 for active and inactive
after getting the data I render it with like this
"columns": [
{
"data": "name"
},
{
"data": "surname"
},
{
"data": "status",
"render": function(data, type, row) {
if (data == '1') {
return '<div class="badge badge-green">active</div>';
} else {
return '<div class="badge badge-red">inactive</div>';
}
}
}
]
And after rendering the data I am getting dynamically all the statuses in the table and appened it to select element for extra filteration.
I used initComplete function to get values and append it as follows:
initComplete: function() {
// select status column
dataTable.column(2).data().unique().sort().each(function(data, j) {
$('#filterByStatus').append('<option value="' + data + '">' + data + '</option>');
});
}
The thing is since my actual data are 0s and 1s the function I am using is printing 0 and 1 in the select option not the rendered data which are active and inactive.
How to to get the rendered values of cell? like this
<option value="active">active</option>
<option value="inactive">inactive</option>

I had the same issues and i fixed it by calling the same function again. hope this helps
"initComplete": function (){
this.api().columns([2,7,9]).every( function ()
{
var column = this;
var select = $('<select><option value=""></option></select>').appendTo( $(column.footer()).empty()).on( 'change', function () {var val = $.fn.dataTable.util.escapeRegex($(this).val());
column.search( val ? '^'+val+'$' : '', true, false ).draw();
});
$col=column[0];
if($col==9){
column.data().unique().sort().each( function ( d, j ){
$val=StatusFormatter(d);
select.append( '<option value="'+$val+'">'+$val+'</option>' )
});
}
else{
column.data().unique().sort().each( function ( d, j ){
select.append( '<option value="'+d+'">'+d+'</option>' )
});
}
});
}

Related

Thymeleaf: Keeping selected row in a Datatable after submitting

I have a Thymeleaf template with a Datatable (1.10.15). I have generated this code to keep the selected row after submitting, but It's not working and I don;t have any javascript error
<script th:inline="javascript">
/*<![CDATA[*/
$(document).ready(function() {
var table = $('#deviceEventTable').DataTable( {
order: [[ 0, "desc" ]],
select: true,
bLengthChange: false,
stateSave: true,
pageLength: 20,
initComplete: function() {
var api = this.api();
if (localStorage.getItem( 'DataTables_selected' )!=null && localStorage.getItem( 'DataTables_selected' ) != 'undefined') {
var selected = localStorage.getItem( 'DataTables_selected' ).split(',');
selected.forEach(function(s) {
api.row(s).select();
})
}
}
});
table.on('select.dt deselect.dt', function() {
localStorage.setItem( 'DataTables_selected', table.rows( { selected: true }).toArray() )
})
} );
/*]]>*/
</script>
I realize that is not a problem of submitting, when I clock the row does not get selected. It gets selected replacing this code
table.on('select.dt deselect.dt', function() {
localStorage.setItem( 'DataTables_selected', table.rows( { selected: true }).toArray() )
})
for this one:
$('#deviceEventTable tbody').on('click', 'td', function () {
$(this).closest("tr").toggleClass('selected');
});
But then on submitting it dissapears the selected row
You use one variable and overwrite it in strings
var selected = localStorage.getItem( 'DataTables_selected' ).split(',');
var selected = '0';
Just delete var selected = '0'; everything else looks working :)
UPD
You use old dataTable() constructur which returns a jQuery object.
Change it on DataTable() constructur, its return API object with nedded access to rows
var table = $('#deviceEventTable').DataTable( {
...
});
UPD2
Working example with you code
http://jsfiddle.net/y8sar09d/5/

jQuery autocomplete selection event

I have created jQuery UI autocomplete which is working very good. But my requirement is that what I display as list should also select same in text box. But it is not selecting
For example list like XXX (XYZ) but when I select it only select XXX not XXX (XYZ)
what I am missing !!
function getDeptStations() {
$("#txDestination").autocomplete({
source: function (request, response) {
var term = request.term;
var Query = "";
if (lang === "en")
Query = "City_Name_EN";
else if (lang === "fr")
Query = "City_Name_FR";
if (lang === "de")
Query = "City_Name_DE";
if (lang === "ar")
Query = "City_Name_AR";
var requestUri = "/_api/lists/getbytitle('Stations')/items?$select=City_Code," + Query + "&$filter=startswith(" + Query + ",'" + term + "')";
$.ajax({
url: requestUri,
type: "GET",
async: false,
headers: {
"ACCEPT": "application/json;odata=verbose"
}
}).done(function (data) {
if (data.d.results) {
response($.map(eval(data.d.results), function (item) {
return {
label: item[Query] + " (" + item.City_Code + ")",
value: item[Query],
id: item[Query]
}
}));
}
else {
}
});
},
response: function (event, ui) {
if (!ui.content.length) {
var noResult = { value: "", label: "No cities matching your request" };
ui.content.push(noResult);
}
},
select: function (event, ui) {
$("#txDestination").val(ui.item.label);
cityID = ui.item.id;
},
minLength: 1
});
}
Almost there, just return a false from select event.
select: function (event, ui) {
$("#txDestination").val(ui.item.label);
cityID = ui.item.id;
return false;
},
or Simply
select: function (event, ui) {
alert(ui.item.id);
return false;
},
This will guide jquery autocomplete to know that select has set a value.
Update: This is not in the documentation, I figured out by digging into source code, took me some time. But indeed it deserves to be in the doc or in options.
in this case you have to options
the obvious one set value:item[Query] + " (" + item.City_Code + ")" but I am assuming this is not the option.
Handle the selection by yourself first check the api doc and you will see event like below. with event.target you can access your input with ui you can access you selected item.
$( ".selector" ).autocomplete({
select: function( event, ui ) {}
});
I understand its been answered already. but I hope this will help someone in future and saves so much time and pain.
After getting the results in autocomplete you can use below code for keeping the value in the autocomplete textbox field. (you can replace 'CRM.$' with '$' or 'jQuery' depending on your jQuery version)
select: function (event, ui) {
var label = ui.item.label;
var value = ui.item.value;
//assigning the value to hidden field for saving the id
CRM.$( 'input[name=product_select_id]' ).val(value);
//keeping the selected label in the autocomplete field
CRM.$('input[id^=custom_78]').val(label);
return false;
},
complete code is below: This one I did for a textbox to make it Autocomplete in CiviCRM. Hope it helps someone
CRM.$( 'input[id^=custom_78]' ).autocomplete({
autoFill: true,
select: function (event, ui) {
var label = ui.item.label;
var value = ui.item.value;
// Update subject field to add book year and book product
var book_year_value = CRM.$('select[id^=custom_77] option:selected').text().replace('Book Year ','');
//book_year_value.replace('Book Year ','');
var subject_value = book_year_value + '/' + ui.item.label;
CRM.$('#subject').val(subject_value);
CRM.$( 'input[name=product_select_id]' ).val(ui.item.value);
CRM.$('input[id^=custom_78]').val(ui.item.label);
return false;
},
source: function(request, response) {
CRM.$.ajax({
url: productUrl,
data: {
'subCategory' : cj('select[id^=custom_77]').val(),
's': request.term,
},
beforeSend: function( xhr ) {
xhr.overrideMimeType( "text/plain; charset=x-user-defined" );
},
success: function(result){
result = jQuery.parseJSON( result);
//console.log(result);
response(CRM.$.map(result, function (val,key) {
//console.log(key);
//console.log(val);
return {
label: val,
value: key
};
}));
}
})
.done(function( data ) {
if ( console && console.log ) {
// console.log( "Sample of dataas:", data.slice( 0, 100 ) );
}
});
}
});
PHP code on how I'm returning data to this jquery ajax call in autocomplete:
/**
* This class contains all product related functions that are called using AJAX (jQuery)
*/
class CRM_Civicrmactivitiesproductlink_Page_AJAX {
static function getProductList() {
$name = CRM_Utils_Array::value( 's', $_GET );
$name = CRM_Utils_Type::escape( $name, 'String' );
$limit = '10';
$strSearch = "description LIKE '%$name%'";
$subCategory = CRM_Utils_Array::value( 'subCategory', $_GET );
$subCategory = CRM_Utils_Type::escape( $subCategory, 'String' );
if (!empty($subCategory))
{
$strSearch .= " AND sub_category = ".$subCategory;
}
$query = "SELECT id , description as data FROM abc_books WHERE $strSearch";
$resultArray = array();
$dao = CRM_Core_DAO::executeQuery( $query );
while ( $dao->fetch( ) ) {
$resultArray[$dao->id] = $dao->data;//creating the array to send id as key and data as value
}
echo json_encode($resultArray);
CRM_Utils_System::civiExit();
}
}

DataTables sAjaxSource Json higlight search data

I am trying to implement search highlight on data table ( JSON data is coming and filling up the table from serverside through "sAjaxSource"), Please see the below code for details.
search is working by default, BUT highlight is not working at all.
I alerted data of searchTxt+=$('#search_input').val(); alert("txt" + searchTxt);
and alert is displaying search input box text.
Alert for " alert(""+ aData[j]); " displaying "undefined rather than column data and highlight is not working.
Could anyone shed some light on this ?
Thank you,
Sri
jQuery(document).ready(function() {
var oTable = jQuery('#example').dataTable({
"sDom": '<"#table_header"<"#inner_table_header"<"filtertx">fCT<"filterbtn">>>tipl',
"sAjaxSource": ajaxURL,
"bDeferRender": true,
"bProcessing" : true,
"bJQueryUI": true,
"sScrollY": 500,
"aaSorting": [[0, 'desc']],
"aoColumns": [
{ "mData": "name" },
{ "mData": "flag" }
],
"oSearch": {"sSearch": "",
"bSmart": true,
"bRegex": false},
"sPaginationType": "paginate",
"fnRowCallback": function( nRow, aData, iDisplayIndex, iDisplayIndexFull ) {
$(nRow).addClass('clickable');
$(nRow).attr('onClick', "editPopup(" + aData['conditionId'] + ")");
},
"fnDrawCallback": function( oSettings ) {
$(expandWrapper);
}
});
$("#example_filter label").attr("for", "search_input");
$("#example_filter input").attr({
"id": "search_input",
"placeholder" : 'search'
});
oTable.fnSearchHighlighting();
});
jQuery.fn.dataTableExt.oApi.fnSearchHighlighting = function(oSettings) {
oSettings.oPreviousSearch.oSearchCaches = {};
oSettings.oApi._fnCallbackReg( oSettings, 'aoRowCallback', function( nRow, aData, iDisplayIndex, iDisplayIndexFull) {
var searchStrings = [];
var oApi = this.oApi;
var cache = oSettings.oPreviousSearch.oSearchCaches;
// Global search string
// If there is a global search string, add it to the search string array
if (oSettings.oPreviousSearch.sSearch) {
searchStrings.push(oSettings.oPreviousSearch.sSearch);
}
// Individual column search option object
// If there are individual column search strings, add them to the search string array
searchTxt=$('#filter_input input[type="text"]').val();
searchTxt+=$('#search_input').val();
alert("txt" + searchTxt);
if ((oSettings.aoPreSearchCols) && (oSettings.aoPreSearchCols.length > 0)) {
for (var i in oSettings.aoPreSearchCols) {
if (oSettings.aoPreSearchCols[i].sSearch) {
searchStrings.push(searchTxt);
}
}
}
// Create the regex built from one or more search string and cache as necessary
if (searchStrings.length > 0) {
var sSregex = searchStrings.join("|");
if (!cache[sSregex]) {
// This regex will avoid in HTML matches
cache[sSregex] = new RegExp("("+escapeRegExpSpecialChars(sSregex)+")(?!([^<]+)?>)", 'i');
}
var regex = cache[sSregex];
}
// Loop through the rows/fields for matches
jQuery('td', nRow).each( function(i) {
// Take into account that ColVis may be in use
var j = oApi._fnVisibleToColumnIndex( oSettings,i);
// Only try to highlight if the cell is not empty or null
alert(""+ aData[j]);
if (aData[j]) {
// If there is a search string try to match
if ((typeof sSregex !== 'undefined') && (sSregex)) {
alert("here");
this.innerHTML = aData[j].replace( regex, function(matched) {
return "<span class='filterMatches'>"+matched+"</span>";
});
}
// Otherwise reset to a clean string
else {
this.innerHTML = aData[j];
}
}
});
return nRow;
}, 'row-highlight');
return this;
};
Wherever the search functionality is and if you are using mData to populate json data, use mData information to retrieve the column data and highlight ( DO NOT use indexes to retrieve column data for search and highlight)
var colProp = oSettings.aoColumns[i].mData;
jQuery('td', nRow).each( function(i) {
/* Take into account that ColVis may be in use
var j = oApi._fnVisibleToColumnIndex( oSettings,i);
Only try to highlight if the cell is not empty or null
*/
var colProp = oSettings.aoColumns[i].mData;
if (aData[colProp] !== undefined && aData[colProp] !== null && aData[colProp] !== "") {
// If there is a search string try to match
if ((typeof sSregex !== 'undefined') && (sSregex)) {
var mapObj = {
'®' : "\u00AE",
'™' : "\u2122",
'"' : "\u201C",
' ' : " "
};
aData[colProp] = aData[colProp].replace(/(®)|(™)|(")|( )/gi, function(matched){
return mapObj[matched];
});
this.innerHTML = aData[colProp].replace( regex, function(matched) {
return "<span class='filterMatches'>"+matched+"</span>";
});
}
else {
this.innerHTML = aData[colProp];
}
}
});
return nRow;
}, 'row-highlight');
return this;

Refreshing Pagination in DataTables?

I'm having a strange issue that's only arising in my dataTable in select environments. I've written a function that allows the user to delete a row, then if it's the last row on that particular page, reload the Table and send the user to the 'new' last page.
However, on some servers, it's not working properly -- I think it has to do with the fact that with after using fnClearTable and fnDraw, the pagination of the table still holds the last 'empty' page.
Here's the function I'm working with now:
function fnDelete(elem) {
if (selected.length > 0) {
var c;
c = confirm("Are you sure you want to delete the selected Agency?");
if (c) {
var deleteURL = urlstr.substring(0, urlstr.lastIndexOf("/") + 1) + "delete.do";
deleteRecord(deleteURL, selected[0]);
if ($(".tableViewer tbody tr:visible").length === 1) {
oTable.fnClearTable();
oTable.fnDraw();
oTable.fnPageChange("last");
}}}}
In addition, here's my delet function.
function deleteRecord(deleteURL, iid){
var didDelete = false;
jQuery.ajax({
type: "POST",
url: deleteURL,
dataType:"html",
data:"recordID="+iid,
async : false,
success:function(response){
didDelete = true;
oTable.fnDraw(true);
selected = [];
selectedRecord = [];
enableButtons(selected);
},
error:function (xhr, ajaxOptions, thrownError){
<%-- is the message in a range we can handle? --%>
if ((xhr.status >=400) && (xhr.status < 500)) {
alert(xhr.responseText);
}
else {
alert('<spring:message arguments="" text="Internal Server Error" code="ajax.internal.server.error"/>');
}
}
});
return didDelete;
}
Again, this issue is only coming up on certain computers. Can anyone help?
Also, here's the configuration for my DataTable::
oTable = $('#${tableName}_grid').dataTable({
bDestroy: true,
bSort: true,
bFilter: true,
bJQueryUI: true,
bProcessing: true,
bAutoWidth: true,
bInfo: true,
bLengthChange: true,
iDisplayLength: ${sessionScope.displayLength},
sPaginationType: 'full_numbers',
bServerSide: true,
sAjaxSource: "<c:url value='${dataUrl}'/>",
aaSorting: [<c:forEach items="${sortInfo}" var="oneSort"> [${oneSort.columnIndex},'${oneSort.ascending ? "asc":"desc"}']</c:forEach>],
aoColumns: [
<c:forEach items="${columns}" var="curCol" varStatus="colLoop">
{sName: '${curCol.fieldName}', bSortable: ${curCol.sortable}, bSearchable: false, sTitle: "<c:out value='${curCol.title}'/>", sType: '${curCol.displayType}', bVisible:${curCol.visible}, vdbType:'${curCol.vdbType}', sClass:'${curCol.displayType}'}${colLoop.last ? '' : ','}
</c:forEach>
],
aoColumnDefs:[{sClass:"color_col", aTargets:['color']}],
fnRowCallback: function( nRow, aData, iDisplayIndex ) {
$('#${tableName}_grid tbody tr').each( function () {
if ($.inArray(aData[0], selected)!=-1) {
$(this).addClass('row_selected');
}
});
return nRow;
},
fnInfoCallback: function( oSettings, iStart, iEnd, iMax, iTotal, sPre ) {
if(myPos>=iStart && myPos<=iEnd){
//alert(myPos+" visible")
}else{
selected = [];
selected = [];
selectedRecord = [];
$('tr').removeClass('row_selected');
enableButtons(selected);
}
},
fnDrawCallback: function ( oSettings ) {
$('#${tableName}_grid tbody tr').each( function () {
var iPos = myPos = oTable.fnGetPosition( this );
if (iPos!=null) {
var aData = oTable.fnGetData( iPos );
if ($.inArray(aData[0], selected)!=-1) {
$(this).addClass('row_selected');
}
}
var htxt = '';
$(this).find('.color').filter(function(i,tdata){
htxt = '';
htxt = '#'+($(tdata).text());
return true;
}).css("background",htxt);
$(this).dblclick( function(){
var iPos = myPos = oTable.fnGetPosition(this);
var aData = oTable.fnGetData(iPos);
var iId = aData[0];
selected = [];
selectedRecord = [];
selected.push(iId);
selectedRecord.push(aData);
$('tr').removeClass('row_selected');
$(this).addClass('row_selected');
enableButtons(selected);
<%-- in case there is no edit button or its enablement is more complex,
// click the button instead of assuming it will call fnEdit.
// Do first() because jQuery is returning the same element multiple times.--%>
$(".${tableName}_bttns > span.edit-doubleclick:not(.disabld)").first().click();
});
$(this).click( function () {
var iPos = myPos = oTable.fnGetPosition(this);<%-- row index on_this_page --%>
var aData = oTable.fnGetData(iPos);
var iId = aData[0];
var is_in_array = $.inArray(iId, selected);
<%-- alert("iPos: " + iPos + "\nData: " + aData + "\niId: " + iId + "\nselected: " + selected + "\nis_in_array: " + is_in_array); --%>
selected = [];
selectedRecord = [];
if (is_in_array==-1) {
selected.push(iId);
selected.sort(function(a,b){return a-b});
selectedRecord.push(aData);
selectedRecord.sort(function(a,b){return a[0]-b[0]});
}
else {
selected = $.grep(selected, function(value) {
return value != iId;
});
selectedRecord = $.grep(selectedRecord, function(value) {
return value != aData;
});
}
if ( $(this).hasClass('row_selected') ) {
$(this).removeClass('row_selected');
}
else {
$('#${tableName}_grid tr').removeClass('row_selected');
$(this).addClass('row_selected');
}
enableButtons(selectedRecord);
});
});
} ,
"sDom": '<"H"lTfr>t<"F"ip>',
"oTableTools":{
"aButtons":[ {
"sExtends":"print",
"bShowAll": true,
"sInfo": printmsg,
"sButtonClass":"ui-icon fg-button ui-button edit-print DTTT_button_print",
"sButtonClassHover":"ui-icon fg-button ui-button edit-print DTTT_button_print"
} ] }
});
$('#${tableName}_grid_filter input').attr("maxlength", "255").attr("size", "35");
$('#${tableName}_grid').ready(function(){
$(".DTTT_containerc").remove();
BuildToolBarButtons();
var tt;
$(".DTTT_containerc").each(function(){
tt = $(this).find("#Print").attr("title");
$(this).find("#Print").remove();
$(this).find(".DTTT_container").remove();
}
);
$(".DTTT_container > button").attr("title",tt).css("border","1px solid #9597A3").removeClass("ui-state-default");
$(".DTTT_containerc").append($(".DTTT_container").removeAttr("style"));
});
});
Your datatable is configured to load data using ajax. This means that any action against the data happens asynchronously. Specifically, the fnDraw() function allows control to go to the statement where you change the page page before the new data is back from the server. You should move the logic that takes you to the last page to the fnDrawCallback. I believe that should resolve your issue.
Thought I'd write a response to help others to show how I fixed it.
#Gavin was correct in that it was in the wrong place -- I moved the function in question to the sucess callback in AJAX. However, to fix it fully, I had to 'premptively' read what page the deletion was happening on (using fn.PageChange plugin), subtract 1 (bc DataTables is zero-based) and send the user there.
Hope this helps anyone! #Gavin, thank you for your help and for leading me int he right direction!
you can keep on the same page after the table refreshed. you need to use the following snippet to keep your pagination same after refreshing datatable. just copy paste following js code on a separate file and hook it with your current page.
$.fn.dataTableExt.oApi.fnStandingRedraw = function(oSettings) {
if(oSettings.oFeatures.bServerSide === false){
var before = oSettings._iDisplayStart;
oSettings.oApi._fnReDraw(oSettings);
oSettings._iDisplayStart = before;
oSettings.oApi._fnCalculateEnd(oSettings);
}
oSettings.oApi._fnDraw(oSettings);
};
and now, you might be used the "fnDraw" to refresh the dataTable. So now, instead of that code. change it like this.
oTable1.fnStandingRedraw();
Now, your dataTable will keep the same page after refreshing it.

How to pass data to url from jqgrid row if hyperlink is clicked

jqGrid contains quantity column and add to cart button using colmodel below. Inline editing
is used to fill quantity.
If quantity is fileld and add to cart link on other column is clicked, entered quanty is not passed to AddToCart controller. Product id from id field in json data is passed correctly.
How to pass selected quantity to AddToCart controller (using invoked url query string or something other) ?
colmodel is:
{"label":"AddToCart",
"name":"Addtocrt_addtocrt",
"formatter":"showlink",
"formatoptions": {"baseLinkUrl":"http://MySite.com/Store/AddToCart"}
},
{"label":"Quantity",
"name":"Stocks_valkogus",
"editoptions":{"maxlength":10 }
"editable":true
}
Update
Data from server is in json format and row editing mode is used.
rowData.Stocks_valkogus returns undefined.
I tried code below. alert box shows that quantityVal is undefined.
How to retrieve entered quantity?
{"name":"Addtocrt_addtocrt",
"formatter":"dynamicLink",
"formatoptions":{"onClick":addToCartOnClick
}}
function addToCartOnClick(rowId, iRow, iCol, cellValue, e) {
var iCol = getColumnIndexByName($grid, 'Stocks_valkogus') ,
quantityVal = $('#' + $.jgrid.jqID(rowId) + '>td:nth-child(' + (iCol + 1) + '>input').val();
alert(iCol); // returns 3
alert(quantityVal); // returns undefined.
window.location = 'Store/Details?' + $.param({
id: rowId,
quantity: quantityVal
});
}
I understand the problem very good. I agree that both predefined formatter which one can use currently ('showlink' and 'link' formatters) are not flexible enough.
I can suggest you another formatter which you could download here. The usage of the formatter is very easy:
{label: "AddToCart", name: "Addtocrt_addtocrt", formatter: "dynamicLink",
formatoptions: {
url: function (cellValue, rowId, rowData) {
return '/Store/AddToCart' + rowId + '?' +
$.param({
quantity: rowData.Stocks_valkogus
});
}
}
}
The url defined as function will be used in the <a> as the value of href attribute.
Additionally to the url formatoptions the 'dynamicLink' formatter supports target option (with the same meaning as by 'showlink'), cellValue which can be also function and onClick callback with rowId, iRow, iCol, cellValue, e as parameters. If the onClick callback is defined the value of url will be ignored. So one can skip the definition of the formatter option url.
The demo demonstrate the usage of the 'dynamicLink' formatter:
The current code of the formatter: 'dynamicLink' you can find below:
/*global jQuery */
(function ($) {
'use strict';
/*jslint unparam: true */
$.extend($.fn.fmatter, {
dynamicLink: function (cellValue, options, rowData) {
// href, target, rel, title, onclick
// other attributes like media, hreflang, type are not supported currently
var op = {url: '#'};
if (typeof options.colModel.formatoptions !== 'undefined') {
op = $.extend({}, op, options.colModel.formatoptions);
}
if ($.isFunction(op.target)) {
op.target = op.target.call(this, cellValue, options.rowId, rowData, options);
}
if ($.isFunction(op.url)) {
op.url = op.url.call(this, cellValue, options.rowId, rowData, options);
}
if ($.isFunction(op.cellValue)) {
cellValue = op.cellValue.call(this, cellValue, options.rowId, rowData, options);
}
if ($.fmatter.isString(cellValue) || $.fmatter.isNumber(cellValue)) {
return '<a' +
(op.target ? ' target=' + op.target : '') +
(op.onClick ? ' onclick="return $.fn.fmatter.dynamicLink.onClick.call(this, arguments[0]);"' : '') +
' href="' + op.url + '">' +
(cellValue || ' ') + '</a>';
} else {
return ' ';
}
}
});
$.extend($.fn.fmatter.dynamicLink, {
unformat: function (cellValue, options, elem) {
var text = $(elem).text();
return text === ' ' ? '' : text;
},
onClick: function (e) {
var $cell = $(this).closest('td'),
$row = $cell.closest('tr.jqgrow'),
$grid = $row.closest('table.ui-jqgrid-btable'),
p,
colModel,
iCol;
if ($grid.length === 1) {
p = $grid[0].p;
if (p) {
iCol = $.jgrid.getCellIndex($cell[0]);
colModel = p.colModel;
colModel[iCol].formatoptions.onClick.call($grid[0],
$row.attr('id'), $row[0].rowIndex, iCol, $cell.text(), e);
}
}
return false;
}
});
}(jQuery));
I plan to place the code of the formatter and some other plugins to jqGrid on the github.
UPDATED: Free jqGrid extends the options of formatter: "showlink" (see the wiki article and the answer). So one don't need to use the formatter: "dynamicLink" in case of usage free jqGrid.

Categories

Resources