jqGrid custom input element needs handle to parent table - javascript

I'm using jqGrid to build a custom inline entry widget on a page. The relevant part of the jqjGrid setup is:
colModel:[ {
// Other columns removed.
{name:'ship',index:'ship', width:90, editable: true, sortable: false,
edittype: "custom",
editoptions:{ custom_element: customElement,
custom_value: customValue} }
],
And my callback function is:
function customElement(value, options) {
var a = $("<input>").attr({
type: 'text',
size: 2,
value: value,
style: 'float: left'
}).add(
$("<span>").attr({
style: 'float: left; margin-top: 2px;',
'class': 'ui-icon ui-icon-search'
}).click(function() {
// My custom function here.
})
).appendTo($("<div>"));
return a;
}
This all works properly.
However, I'm building a library to manage several jqgrid tables on a page. I'd like to use the same function to build the custom elements on several of those tables. The problem is that this particular click() function needs to know which jquery table it's dealing with.
I can get the table ID through a hacky way at the beginning of customElement and pass it in the closure to the function:
var fieldID = options.id;
var rowID = fieldID.replace(/_.*/, "");
var containingTable = $("#" + rowID + "_id").closest("table");
But this assumes that the column "id" exists in the current jqGrid, and it's an earlier (leftward) column. I can't use the "ship" column because it hasn't been created yet. I can't assume there are other rows in the table that would have a "ship" column either.
How can I, in a custom_element handler, reliably get a handle to the "calling" table?

I agree that it's a problem in the current code of jqGrid. There are no simple and elegant way to get the id of the grid for which the control are created.
One workaround you already suggested. I can suggest you one more version to get the id of "the calling table".
Custom element can be used for every editing mode: inline editing, form editing and cell editing. The click handle receive Event object e
.click(function(e) {
// My custom function here.
})
which you can to detect the id of the "the calling grid". In case of inline editing or cell editing the detection is the most easy. It will be
.click(function(e) {
var $grid = $(e.target).closest('table.ui-jqgrid-btable');
...
})
Inside of click event handler of the form editing you can use
.click(function(e) {
// you can do the following
var $t = $(e.target).closest('table.EditTable'),
tid = $t.attr('id'); // id=TblGrid_list
if (typeof tid === "string" && tid.substr(0, 8) === 'TblGrid_') {
var gridId = tid.substr(8);
}
var grid = $('#' + $.jgrid.jqID(gridId));
// or the following
var $f = $(e.target).closest('form.FormGrid'),
fid = $f.attr('id'); // id=FrmGrid_list
if (typeof fid === "string" && fid.substr(0, 8) === 'FrmGrid_') {
var grid_id = tid.substr(8);
}
var mygrid = $('#' + $.jgrid.jqID(grid_id));
...
})
The code above use the fact that the editing form contains two elements which ids will be constructed based on the id of the grid: the <table> element inside of the editing form has the id="TblGrid_list" if the grid id="list" and the <form> element has the id="FrmGrid_list".
The usage of $('#' + $.jgrid.jqID(gridId)) is more safe as $('#' + gridId) because it gives correct results in case when the grid id contain meta characters. The jqID function is very easy (see here). It makes just escaping of the meta characters used in the jQuery selector.

Related

JQuery Datatables search within input and select

Using Jquery Datatables with inputs and selects as shown here: http://datatables.net/examples/api/form.html
or if I used a custom column render handler to produce the input and selects how can I make the global table search work?
If you view the example you'll notice that only the first column, the read only one, is included in the search, what can I do to include the other columns in the search?
If you view the example in the link in my question and type "Tokyo" into the search all rows are returned. This is because "Tokyo" is an option in all dropdowns. I would want only rows with Tokyo selected to show. If you type in "33" you see no rows even though the first row has a value of "33" in the first column.
I can't seem to find any documentation on how to define what the search value is for a particular cell in a datatable.
It is not very well documented. And it seems to work differently, or not work at all, between (sub)versions. I think dataTables is intended to automatically detect HTML-columns, but for some reason, most of the times, it doesnt. The safest way is to create your own search-filter :
$.fn.dataTableExt.ofnSearch['html-input'] = function(value) {
return $(value).val();
};
This will return 33 on <input>'s with value 33, and Tokyo on <select>'s where Tokyo is selected. Then define the desired columns as of type html-input ;
var table = $("#example").DataTable({
columnDefs: [
{ "type": "html-input", "targets": [1, 2, 3] }
]
});
see demo based on http://datatables.net/examples/api/form.html -> http://jsfiddle.net/a3o3yqkw/
Regarding live data: The issue is, that the type based filter only is called once. dataTables then caches the returned values so it not need to "calculate" all the values over and over. Luckily, dataTables 1.10.x has a built-in function for cells, rows and pages called invalidate that forces dataTables to reset the cache for the selected items.
However, when dealing with <input>'s there is also the problem, that editing the value not is changing the value attribute itself. So even if you call invalidate(), you will still end up in filtering on the old "hardcoded" value.
But I have found a solution for this. Force the <input>'s value attribute to be changed with the <input>'s current value (the new value) and then call invalidate :
$("#example td input").on('change', function() {
var $td = $(this).closest('td');
$td.find('input').attr('value', this.value);
table.cell($td).invalidate();
});
For textareas use text() instead :
$("#example td textarea").on('change', function() {
var $td = $(this).closest('td');
$td.find('textarea').text(this.value);
table.cell($td).invalidate();
});
This is also the case when dealing with <select>'s. You will need to update the selected attribute for the relevant <option>'s and then invalidate() the cell as well :
$("#example td select").on('change', function() {
var $td = $(this).closest('td');
var value = this.value;
$td.find('option').each(function(i, o) {
$(o).removeAttr('selected');
if ($(o).val() == value) $(o).attr('selected', true);
})
table.cell($td).invalidate();
});
forked fiddle -> http://jsfiddle.net/s2gbafuz/ Try change content of the inputs and/or the dropdowns, and search for the new values ...
If the point here is to search through all the inputs within a table based on the live values (and "regular" cells), you might want to build your own custom search ($.fn.DataTable.ext.search.push()):
//custom search function
$.fn.DataTable.ext.search.push((_,__,i) => {
//get current row
const currentTr = dataTable.row(i).node();
//look for all <input>, <select> nodes within
//that row and check whether current value of
//any of those contains searched string
const inputMatch = $(currentTr)
.find('select,input')
.toArray()
.some(input => $(input).val().toLowerCase().includes($('#search').val().toLowerCase()));
//check whether "regular" cells contain the
//value being searched
const textMatch = $(currentTr)
.children()
.not('td:has("input,select")')
.toArray()
.some(td => $(td).text().toLowerCase().includes($('#search').val().toLowerCase()))
//make final decision about match
return inputMatch || textMatch || $('#search').val() == ''
});
The complete DEMO of this approach you may find below:
const srcData = [{id:1,item:'apple',category:'fruit'},{id:2,item:'banana',category:'fruit'},{id:3,item:'goosberry',category:'berry'},{id:4,item:'eggplant',category:'vegie'},{id:5,item:'carrot',category:'vegie'}];
const dataTable = $('table').DataTable({dom:'t',data:srcData,columns:[{title:'Id',data:'id'},{title:'Item',data:'item',render:data=>`<input value="${data}"></input>`},{title:'Category',data:'category',render:data=>`<select>${['fruit', 'vegie', 'berry'].reduce((options, item) => options+='<option value="'+item+'" '+(item == data ? 'selected' : '')+'>'+item+'</option>', '<option value=""></option>')}</select>`}]});
$.fn.DataTable.ext.search.push((_,__,i) => {
const currentTr = dataTable.row(i).node();
const inputMatch = $(currentTr)
.find('select,input')
.toArray()
.some(input => $(input).val().toLowerCase().includes( $('#search').val().toLowerCase()));
const textMatch = $(currentTr)
.children()
.not('td:has("input,select")')
.toArray()
.some(td => $(td).text().toLowerCase().includes($('#search').val().toLowerCase()))
return inputMatch || textMatch || $('#search').val() == ''
});
$('#search').on('keyup', () => dataTable.draw());
<!doctype html><html><head><script type="application/javascript" src="https://code.jquery.com/jquery-3.3.1.min.js"></script><script type="application/javascript" src="https://cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js"></script><link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.19/css/jquery.dataTables.min.css"></head><body><input id="search"></input><table></table></body></html>
This should search the entire table instead of specific column(s).
var table = $('#table').DataTable();
$('#input').on('keyup', function() {
table.search(this.val).draw();
});
Best thing to do here is just update the cell container to the new value from the input and keep the datatable data object sync with the UI input:
$("#pagesTable td input,#pagesTable td select").on('change', function () {
var td = $(this).closest("td");
dataTable.api().cell(td).data(this.value);
});
Replace you input by Textarea, and add the css below. It will make your textarea looks like an input.
textarea{
height: 30px !important;
padding: 2px;
overflow: hidden;
}

tooltip doesn't work in a table cell

My question might seems long, but I am trying to give relevant information in detail so please bear with me.
I am using tooltipster tooltip plugin (http://iamceege.github.io/tooltipster/) on my website. However my question is more related to JS instead of tooltipster plug in. I am easily able to integrate the tooltip plugin on my website and it is working just fine on images, buttons, etc where the content is static. However, I am populating tables dynamically based on the JSON response and I can't get the tooltip working on the table cells.
First I thought there might be some problem with the plugin. In a flash I switched to bootstrap inbuilt tooltip and I am facing the same problem. I can get bootstrap tooltip to work on other other elements apart from the table cells.
Here is my JS where I am adding the class customToolTip
function addBetTypeProductsToLegend(table) {
var betType = $.data(table, 'BetTableData').betType,
legendRow = $.data(table, 'BetTableData').legendRow,
productNotFount = true,
td;
$.each(betType.products, function(index,value) {
var betTypeHint = 'betTypeId_' + value.id + '_hint';
td = element.create('td');
element.setId(td, value.id);
element.setClassName(td, 'customToolTip'); // adding customToolTip class
element.setTitle(td, window[ 'betTypeId_' + value.id + '_hint']); // setting respective title tags
element.setInnerHtml(td, getBrandBetName(value.name));
legendRow.appendChild(td);
productNotFount = false;
});
// Racing Specials
td = element.create('td');
element.setId(td, betType.id);
element.setInnerHtml(td, betType.name);
if (productNotFount) legendRow.appendChild(td);
}
This is how I am assigning class name and title attributes
var element = {
create: function(htmlIndentifier) {
return document.createElement(htmlIndentifier);
},
setClassName: function(element, className) {
element.className = className;
},
setTitle: function(element, title) {
element.title = title;
}
}
JS plugin initialization
$(document).ready(function() {
$('.customToolTip').tooltipster({
animation: 'fade',
delay: 400,
theme: 'tooltipster-IB',
touchDevices: false,
trigger: 'hover'
});
});
So the above doesn't apply to the table cell I tried to use bootstrap tooltip and initialize the function like this.
$(".customToolTip").tooltip({
placement : 'top'
});
It works fine for other elements apart from table cells.
I tried to set padding as well for tooltip as well
$('.customToolTip').each(function(e) {
var p = $(this).parent();
if(p.is('td')) {
$(this).css('padding', p.css('padding'));
p.css('padding', '0 0');
}
$(this).tooltip({
placement: 'top'
});
});
I followed couple of other posts where people were facing problem with tooltip and table cells
bootstrap "tooltip" and "popover" add extra size in table
https://github.com/twbs/bootstrap/issues/5687
Seems like I have deal with the layout issue later on first I need to show the custom tooltip instead of default title attribute.
Your initialization starts on document ready, when table does not exist in DOM yet. So $('.customToolTip') does not find those.
What you need is to make function, something like this:
function BindTooltips(target) {
target = target || $(document);
target.find('.customToolTip').tooltipster({
animation: 'fade',
delay: 400,
theme: 'tooltipster-IB',
touchDevices: false,
trigger: 'hover'
});
}
And launch it on document ready, so it will find all .customToolTip in your document.
Then after your table is being inserted into dom launch this function again and provide container (table) as argument.

JQuery get calling <script> tag when dynamically loaded

How can I locate the tag which calls a JQuery script, when
the tag is dynamically loaded, so won't be the last
tag on the page?
I'm using the MagicSuggest autosuggest library. I want to give certain suggested items a different background color depending on their contents, which I'm currently doing by adding JQuery inside a tag, which I'm adding on to the String which is returned to be rendered inside the selection div. Then, to get the div the item is suggested in, I need to essentially get the parent() of the tag, and change it's css() properties. How can I get this current script tag however?
I'm currently assigned each new tag an id generated from incrementing a JS variable - which works, but isn't very 'nice'! Is there anyway I can directly target the tag with JQuery?
If it perhaps makes it clearer, here is my current selectionRenderer function.
selectionRenderer: function(a){
var toRet = a.english;
var blueBgScript = "<script id=ft" + freeTextFieldID + ">$('#ft" + freeTextFieldID + "').parent().css('background', 'blue');</script>"
if(a.id==a.english){
toRet += blueBgScript;
freeTextFieldID++;
}
return toRet;
},
Why don't you add some code at afterrender event instead? Add some tag to flag the options that need a different background, then detect the parents and add a class (or edit the bg property) or whatever you like:
var newMS = $('#idStr').magicSuggest({
data: 'states.php',
displayField: 'english',
valueField: 'id',
selectionRenderer: function(a){
var toRet = a.english;
if(a.id==a.english) toRet = "<span class='freetext'>" + toRet + "</span>";
return toRet;
},
});
$(newMS).on('selectionchange', function(event,combo,selection){
var selDivs = $(event.target._valueContainer[0].parentNode).children('div'); //Get all the divs in the selction
$.each(selDivs,function(index,value){ //For each selected item
var span = $(value).children('.freetext'); //It if contains a span of class freetext
if(span.length == 1) $(value).css('background','blue'); //Turn the background blue
});

jQuery in-place-editor to use jQuery autocomplete input field

Background
Creating a WYSIWYG editor that uses Dave Hauenstein's edit-in-place and jQuery's autocomplete plug-in.
Source Code
The code has the following parts: HTML, edit-in-place, and autocomplete.
HTML
The HTML element that becomes an edit-in-place text field:
<span class="edit" id="edit">Edit item</span>
Edit In Place
The JavaScript code that uses the edit-in-place plugin:
$('#edit').editInPlace({
url : window.location.pathname,
hover_class : 'inplace_hover',
params : 'command=update-edit',
element_id : 'edit-ac',
on_edit : function() {
return '';
}
});
The on_edit is custom code to call a function when the user clicks on the associated span element. The value returned is used to seed the text input field. In theory, the plugin should replace the span element in the DOM with an input element similar to:
<input type="text" id="edit-ac" />
Autocomplete
The autcomplete code:
$('#edit-ac').autocomplete({
source : URL_BASE + 'search.php',
minLength : 2,
delay : 25
});
Problem
It seems that the timing for the autocomplete code is incorrect with respect to the timing for the edit-in-place code.
I think that the edit-in-place plugin needs to call the autocomplete code snippet after the input field has been added to the DOM.
Question
How would you integrate the two plugins so that when a user clicks on the edit-in-place field that the autocomplete code provides autocomplete functionality on the DOM element added by edit-in-place?
Thank you!
Solution
Modify the jQuery in-place-editor source code by instructing the code to append an identifier onto the input field.
jQuery in-place-editor Updates
This section details the updates required.
Type Definition
Provide new attributes in the default settings:
editor_id: "inplace_id", // default ID for the editor input field
on_create: null, // function: called after the editor is created
inputNameAndClass
Change the inputNameAndClass function to use the editor_id setting:
/**
* Returns the input name, class, and ID for the editor.
*/
inputNameAndClass: function() {
var result = ' name="inplace_value" class="inplace_field" ';
// DJ: Append the ID to the editor input element.
if( this.settings.editor_id ) {
result += 'id="' + this.settings.editor_id + '" ';
}
return result;
},
replaceContentWithEditor
Change the replaceContentWithEditor function to call the create function:
replaceContentWithEditor: function() {
var buttons_html = (this.settings.show_buttons) ? this.settings.save_button + ' ' + this.settings.cancel_button : '';
var editorElement = this.createEditorElement(); // needs to happen before anything is replaced
/* insert the new in place form after the element they click, then empty out the original element */
this.dom.html('<form class="inplace_form" style="display: inline; margin: 0; padding: 0;"></form>')
.find('form')
.append(editorElement)
.append(buttons_html);
// DJ: The input editor is part of the DOM and can now be manipulated.
if( this.settings.on_create ) {
this.settings.on_create( editorElement );
}
},
Autocomplete Coupling
The autocomplete functionality can now be activated the edit-in-place is revealed.
Combined Call
The HTML snippet remains the same as before. The new call to editInPlace resembles:
$('#edit').editInPlace({
url : window.location.pathname,
hover_class : 'inplace_hover',
params : 'command=update-edit',
editor_id : 'edit-ac',
on_create : function( editor ) {
$('#edit-ac').autocomplete({
source : URL_BASE + 'search.php',
minLength : 2,
delay : 25
});
},
on_edit : function() {
return '';
}
});
This attaches the autocomplete function to the in-place-editor whenever the in-place-editor is activated.

How do I manipulate a jqGrid's search/filters?

I have a jqGrid with a navBar that has search: true and multipleSearch: true. I would like to add a button to my UI that automatically adds an additional rule to the search.
I've tried manipulating the postData for the filter directly, but values added this way don't show up in the search UI.
I've also tried accessing the search box directly using jQuery, like this:
$('#fbox_list').searchFilter().add();
$('#fbox_list .sf .data input').each(function(index) {
alert($(this).val());
});
But, in addition to feeling hackish, it only works if the user has already clicked on the search button (the fbox_list div is not constructed on load).
Has anyone else dealt with an issue like this?
For the sake of posterity, here is the hack I'm currently using. The grid has an ID of list and the pager has an ID of pager:
jQuery(document).ready(function() {
//Initialize grid.
//Initialize the navigation bar (#pager)
//Hack to force creation of the search grid.
//The filter's ID is of the form #fbox_<gridId>
jQuery('#pager .ui-icon-search').click();
jQuery('#fbox_list').searchFilter().close();
//Example button events for adding/clearing the filter.
jQuery("#btnAddFilter").click(function() {
//Adds a filter for the first column being equal to 'filterValue'.
var postFilters = jQuery("#list").jqGrid('getGridParam', 'postData').filters;
if (postFilters) {
$('#fbox_list').searchFilter().add();
}
var colModel = jQuery("#list").jqGrid('getGridParam', 'colModel');
//The index into the colModel array for the column we wish to filter.
var colNum = 0;
var col = colModel[colNum];
$('#fbox_list .sf .fields select').last().val(col.index).change();
$('#fbox_list .sf .data input').last().val('filterValue');
$('#fbox_list .sf .ops select.field' + colNum).last().val('eq').change();
$('#fbox_list').searchFilter().search();
});
jQuery("#btnClearFilter").click(function() {
$('#fbox_list').searchFilter().reset();
});
});
If you mean the filter toolbar, you can do this: (status is the col name -- so, replace "#gs_status" w/ "#gs_" + your_col_name
jQuery("#distributor_grid").jqGrid('showCol',['status']);
jQuery(".ui-search-toolbar #gs_status")
.val('ALL')
;
$('#distributor_grid').RefreshData(); // triggers toolbar
to clear inputs, selects and reset grid
$("td#refresh_navGrid").click();

Categories