Creating a link in JQGrid - javascript

I need to make all cells of a column, in my JQgrid, a link, which calls a javascript function with the cell value, to be passed for some query on the server side. I have seen html link column in jqGrid
but it is not working out. here is what I have,
colModel:[
{name:'name',width:300,formatter:link}
]
and the link function is
function link(cellvalue, options, rowObject) {
alert('<a href="javascript:logForProv(\''+cellvalue+'\',\''+$('#datepicker1').val()+'\',\''+$('#datepicker2').val()+'\');">');
return "<a href='javascript:logForProv(\''+cellvalue+'\',\''+$('#datepicker1').val()+'\',\''+$('#datepicker2').val()+'\');'>";
}
Doing this I dont get any data in the column, I also tried using the predefined formatters link and showlink, but they are appending href and id to the URL which is messing up.
Please Help.

When click on providerId edit column you will redirect to edit page of editProvider.
mentionformatter: editLink at providerId colModel for call editLink function. In this way creating link in jqGrid.
Code:
$(document).ready(function(){
//jqGrid
$("#providerList").jqGrid({
url:'<%=request.getContextPath() %>/Admin/getProvidersList',
datatype: "json",
colNames:['Id','Edit','Provider Name'],
colModel:[
{name:'providerId',search:false,index:'providerId',hidden:true},
{name:'providerId',search:false,index:'providerId', width:30,sortable: false, formatter: editLink},
{name:'providerName',index:'providerName', width:200},
rowNum:20,
rowList:[10,20,30,40,50],
rownumbers: true,
pager: '#pagerDiv',
sortname: 'providerName',
viewrecords: true,
sortorder: "desc",
});
$('#gridContainer div:not(.ui-jqgrid-titlebar)').width("100%");
$('.ui-jqgrid-bdiv').css('height', window.innerHeight * .65);
$('#load_providerList').width("130");
$("#providerList").jqGrid('navGrid','#pagerDiv',{edit:false,add:false,del:false},{},{},{}, {closeAfterSearch:true});
$(".inline").colorbox({inline:true, width:"20%"});
});
function editLink(cellValue, options, rowdata, action)
{
return "<a href='<%=request.getContextPath()%>/Admin/editProvider/" + rowdata.providerId + "' class='ui-icon ui-icon-pencil' ></a>";
}

The function logForProv have to be defined on global (top) level.
I recommend you to try better formatter: "dynamicLink" instead, which I described here and which you can download from here (jQuery.jqGrid.dynamicLink.js file). It allows to construct link in jqGrid in very simple and flexible way. You can define onClick callback inside of formatoptions (see the demo). The callback provide rowId, iRow, iCol, cellValue and e as parameters.

Related

Getting search bar to simultaneously work with another search bar [duplicate]

I'm using DataTables (datatables.net) and I would like my search box to be outside of the table (for example in my header div).
Is this possible ?
You can use the DataTables api to filter the table. So all you need is your own input field with a keyup event that triggers the filter function to DataTables. With css or jquery you can hide/remove the existing search input field. Or maybe DataTables has a setting to remove/not-include it.
Checkout the Datatables API documentation on this.
Example:
HTML
<input type="text" id="myInputTextField">
JS
oTable = $('#myTable').DataTable(); //pay attention to capital D, which is mandatory to retrieve "api" datatables' object, as #Lionel said
$('#myInputTextField').keyup(function(){
oTable.search($(this).val()).draw() ;
})
As per #lvkz comment :
if you are using datatable with uppercase d .DataTable() ( this will return a Datatable API object ) use this :
oTable.search($(this).val()).draw() ;
which is #netbrain answer.
if you are using datatable with lowercase d .dataTable() ( this will return a jquery object ) use this :
oTable.fnFilter($(this).val());
You can use the sDom option for this.
Default with search input in its own div:
sDom: '<"search-box"r>lftip'
If you use jQuery UI (bjQueryUI set to true):
sDom: '<"search-box"r><"H"lf>t<"F"ip>'
The above will put the search/filtering input element into it's own div with a class named search-box that is outside of the actual table.
Even though it uses its special shorthand syntax it can actually take any HTML you throw at it.
For recent and new version of DataTables, You should follow these steps:
1- searching option must be true.
2- Hide default search input:
.dataTables_filter {
display: none;
}
3- Add new search input:
<input type="text" id="search">
4- Request search:
$('#search').keyup(function() {
var table = $('.table-meetups').DataTable();
table.search($(this).val()).draw();
});
This one helped me for DataTables Version 1.10.4, because its new API
var oTable = $('#myTable').DataTable();
$('#myInputTextField').keyup(function(){
oTable.search( $(this).val() ).draw();
})
I had the same problem.
I tried all alternatives posted, but no work, I used a way that is not right but it worked perfectly.
Example search input
<input id="searchInput" type="text">
the jquery code
$('#listingData').dataTable({
responsive: true,
"bFilter": true // show search input
});
$("#listingData_filter").addClass("hidden"); // hidden search input
$("#searchInput").on("input", function (e) {
e.preventDefault();
$('#listingData').DataTable().search($(this).val()).draw();
});
More recent versions have a different syntax:
var table = $('#example').DataTable();
// #myInput is a <input type="text"> element
$('#myInput').on('keyup change', function () {
table.search(this.value).draw();
});
Note that this example uses the variable table assigned when datatables is first initialised. If you don't have this variable available, simply use:
var table = $('#example').dataTable().api();
// #myInput is a <input type="text"> element
$('#myInput').on('keyup change', function () {
table.search(this.value).draw();
});
Since: DataTables 1.10
– Source: https://datatables.net/reference/api/search()
I want to add one more thing to the #netbrain's answer relevant in case you use server-side processing (see serverSide option).
Query throttling performed by default by datatables (see searchDelay option) does not apply to the .search() API call. You can get it back by using $.fn.dataTable.util.throttle() in the following way:
var table = $('#myTable').DataTable();
var search = $.fn.dataTable.util.throttle(
function(val) {
table.search(val).draw();
},
400 // Search delay in ms
);
$('#mySearchBox').keyup(function() {
search(this.value);
});
This should be work for you:(DataTables 1.10.7)
oTable = $('#myTable').dataTable();
$('#myInputTextField').on('keyup change', function(){
oTable.api().search($(this).val()).draw();
})
or
oTable = $('#myTable').DataTable();
$('#myInputTextField').on('keyup change', function(){
oTable.search($(this).val()).draw();
})
You could move the div when the table is drawn using the fnDrawCallback function.
$("#myTable").dataTable({
"fnDrawCallback": function (oSettings) {
$(".dataTables_filter").each(function () {
$(this).appendTo($(this).parent().siblings(".panel-body"));
});
}
});
$('#example').DataTable({
"bProcessing": true,
"bServerSide": true,
"sAjaxSource": "../admin/ajax/loadtransajax.php",
"fnServerParams": function (aoData) {
// Initialize your variables here
// I have assign the textbox value for "text_min_val"
var min_val = $("#min").val(); //push to the aoData
aoData.push({name: "text_min_val", value:min_val});
},
"fnCreatedRow": function (nRow, aData, iDataIndex) {
$(nRow).attr('id', 'tr_' + aData[0]);
$(nRow).attr('name', 'tr_' + aData[0]);
$(nRow).attr('min', 'tr_' + aData[0]);
$(nRow).attr('max', 'tr_' + aData[0]);
}
});
In loadtransajax.php you may receive the get value:
if ($_GET['text_min_val']){
$sWhere = "WHERE (";
$sWhere .= " t_group_no LIKE '%" . mysql_real_escape_string($_GET['text_min_val']) . "%' ";
$sWhere .= ')';
}
If you are using JQuery dataTable so you need to just add "bFilter":true. This will display default search box outside table and its works dynamically..as per expected
$("#archivedAssignments").dataTable({
"sPaginationType": "full_numbers",
"bFilter":true,
"sPageFirst": false,
"sPageLast": false,
"oLanguage": {
"oPaginate": {
"sPrevious": "<< previous",
"sNext" : "Next >>",
"sFirst": "<<",
"sLast": ">>"
}
},
"bJQueryUI": false,
"bLengthChange": false,
"bInfo":false,
"bSortable":true
});

Return and refresh select option value on closest tr

I have the below sample code:
<table id='myTable'>
<tr>
<td>Id</td>
<td>Status</td>
<td>Summary</td>
</tr>
</table>
//Sample document ready function
$(document).ready(function(){
$('#myTable').dataTable({
"aoColumnDefs": [
{
"aTargets":[1],
"createdCell": function (td, cellData, rowData, row, col){
if(cellData === 'ordered')
$(td).css('background-color', '#5cb85c');
if(cellData === 'not_ordered')
$(td).css('background-color', '#d9534f');
if(cellData === 'shipped')
$(td).css('background-color', '#f0ad4e');
}
},
{
"aTarget": [2],
"render": function(data, type, full, meta){
if(type === 'display' && data == null) {
data = "enter field summary";
return '<input type="text"' + data +'>';
}
else
return '<input type="text"' + data + '>';
}
}
]
});
//With this function, i want to change the background-color of select field per option selected.However, the val() is returning "undefined"
$('#myTable').on('change',function(){
var optionField = $(this).closest('tr').find('option:selected').val();
if(optionField === 'ordered')
$(this).css({'background-color':'#696969'});
else if(optionField === 'notOrdered')
$(this).css({'background-color':'#e7e7e7'});
else(optionField === 'shipped')
$(this).css({'background-color':'#326f3a'});
}
$('table').on('click', 'input[type="submit"]', function(e)){
var url = 'hiddenAPI.com';
$.ajax({
url: url,
type: "POST",
async: true,
data: {
id: idField,
status: statusField,
summary: summaryField
},
dataType: "json",
success: function (data){
$('#responseField').html('Order ' + idField + ', summary has been posted to the database successfully');
$('#myTable').ajax.reload(); //<- table not refreshing here
},
});
});
});
With the above code, I want to change the background color everytime a select option is selected (determined per value in the code above), also after every post to the database, I want to refresh the whole datatable with the new JSON data. So far the API provided on the datatable site (table.ajax.reload()) isn't working.
Two questions,
1.) With my code above, how can I change the background color of a specific column in datatable after select option is selected?
2.) How do I refresh datatable after every post to the database without having to refresh the entire window/page?
In here:
$(this).css({background-color':'#696969'});
else if(optionField === 'notOrdered')
$(this).css({background-color':'#e7e7e7'});
else(optionField === 'shipped')
$(this).css({background-color':'#326f3a'});
}
the "background-color" string is missing an extra ' at the start
edit: sorry, only fixed a syntax error
After playing around, I ended up fixing this myself.
1.) to refresh ajax data, I ended up calling another ajax call (from another primary function) inside the done function.
2.) to click and return the closest selected option in a table row, I ended up first creating an on click function on the table, and then nested another function for the select on change, then used $(this).closest('tr).find('select').val().

pass an object in jqgrid

I am using jqgrid on my form and I am creating the column delete and want to send the object in javascript function, the code is following
{
name: "action",
align: "center",
sortable: false,
title: false,
fixed: true,
search: false,
formatter: function (cellValue, options, rowObject) {
debugger;
var markup = "<a title=\"%ToolTip%\" href=%Href%;>%Text%</a>";
var replacements = {
"%Text%": "<i class='fa fa-trash' style='color:black'></i>",
"%ToolTip%": UserRoles.messages && UserRoles.messages.ClickHereToDelete
? UserRoles.messages.ClickHereToDelete : "",
"%Href%": "javascript:UserRoles.deleteUserRoles(" + rowObject + ")"
};
markup = markup.replace(/%\w+%/g, function (all) {
return replacements[all];
});
return markup;
}
}
I want to send the object in the function deleteUserRole by this line
"%Href%": "javascript:UserRoles.deleteUserRoles(" + rowObject + ")"
but it is giving me output
<a title="" href="javascript:UserRoles.deleteUserRoles([object" object]);=""><i class="fa fa-trash" style="color:black"></i></a>
can any one help me
Mostly one don't need to create such custom formatter and one can use just formatter: "action" with the corresponding parameters.
It's important to understand that the goal of formatter is providing the HTML fragment which will be placed in cells (in <td>) of the column. The rowObject are typically the input data of the row which format depend on many factors.
What you probably need is to use options.rowId as parameter of UserRoles.deleteUserRoles function. Inside of the function you can use getRowData to get the data based on the rowid.
I would recommend you to read the answer and all old answer referenced i the answer. It shows that one can just use place "<a href='#'><i class='fa fa-trash' style='color:black'></i></a>" by custom formatter **without using any javascript:UserRoles.deleteUserRoles(...) fragment. Instead of that one can implement beforeSelectRow callback which tests in which column the user clicked. If the user clicked on the <a> of "action" column then one can do some custom action. The way is more effective because one don't need bind global function to every <a> element of the column. One can simplify the content of the column by removing <a> and holding only <i class='fa fa-trash' style='color:black'></i> inside of the column. The code of beforeSelectRow callback will be the same.

How to add multi-select filter support to the header, dataTables 1.9

I have been searching for relative posts: Datatables Multi Select Column filter , How to add additional filters to Datatables header? but it does not solve my problem.
I use dataTables 1.9 (legacy one), where I need a filter header exactly at the header like excel does
which will provde a litter button and and then pop up a multi-select(with check boxes) filterer the rows.
So, I need two thing:
a little button to the header and a multi-select displays after click
column filter after multi select close.
Is there a plugin or any simple way to do this? Thank you!
you need to write you desire html in dataTable "fnRender": function (oObj) {} and return that html.
aoColumns: [{
"sName": "ColumnName", sType: 'string', sWidth: '5%', "fnRender": function (oObj) {
var html = '<select>' +
'<option value="volvo">Volvo</option>' +
'<option value="saab">Saab</option>' +
'<option value="mercedes">Mercedes</option>' +
'<option value="audi">Audi</option>' +
'</select>';
return html;
}
}]
html will be added to your desired cell.

Replicate data into JQGrid

I am creating a jqgrid i m creating a row with 2 columns with dropdown box. The dropdowns are getting populated using ajax call. My requirement is I want to replicate this row on click on ADD button in UI. For example for now one row is coming into jqgrid, after clicking ADD button a new row with same content with out refreshing the changed value in first row should be displayed. Is there any way to do that? My jqgrid code is
$("#tbl").jqGrid('GridUnload');
$("#tbl").jqGrid(
{
url : "/searchCriteria.do",
datatype : 'json',
colModel :
[
{name : "test1",label : "TEST1", search : false,cellEdit:true, editable: true,edittype:"select",width:150 ,formatter: createDropDown,title:false},
{name : "test2",label : "TEST2", search : false,cellEdit:true, editable: true,edittype:"select",width:150 ,formatter: createDropDown,title:false}
],
viewrecords: true,
loadonce:true,
width: 1000,
multiselect : true
});
});
You can use a combination of the getLocalRow and addRowData methods to achieve your functionality. Docs for these methods.
Let's say in your HTML you have a button:
<button id="add" type="button">ADD</button>
In your javascript you could have:
<script>
$("#add").click(function(){
var id_of_new_row = something; //you haven't specified which are the exact rows you'd like selected.
//you could use the getDataIDs method to get the row-IDs you're looking for
var new_row_data = $("#gridId").jqGrid('getLocalRow', id_of_new_row));
$("#gridId").jqGrid('addRowData',id_of_new_row+1, new_row_data, "last");
});
</script>

Categories