How to use JQUERY to filter table rows dynamically using multiple form inputs - jquery-plugins

I'm displaying a table with multiple rows and columns. I'm using a JQUERY plugin called uiTableFilter which uses a text field input and filters (shows/hides) the table rows based on the input you provide. All you do is specify a column you want to filter on, and it will display only rows that have the text field input in that column. Simple and works fine.
I want to add a SECOND text input field that will help me narrow the results down even further. So, for instance if I had a PETS table and one column was petType and one was petColor -- I could type in CAT into the first text field, to show ALL cats, and then in the 2nd text field, I could type black, and the resulting table would display only rows where BLACK CATS were found. Basically, a subset.
Here is the JQUERY I'm using:
$("#typeFilter").live('keyup', function() {
if ($(this).val().length > 2 || $(this).val().length == 0)
{
var newTable = $('#pets');
$.uiTableFilter( theTable, this.value, "petType" );
}
}) // end typefilter
$("#colorFilter").live('keyup', function() {
if ($(this).val().length > 2 || $(this).val().length == 0)
{
var newTable = $('#pets');
$.uiTableFilter( newTable, this.value, "petColor" );
}
}) // end colorfilter
Problem is, I can use one filter, and it will display the correct subset of table rows, but when I provide input for the other filter, it doesn't seem to recognize the visible table rows that are remaining from the previous column, but instead it appears that it does an entirely new filtering of the original table. If 10 rows are returned after applying one filter, the 2nd filter should only apply to THOSE 10 rows. I've tried LIVE and BIND, but not working.
Can anyone shed some light on where I'm going wrong? Thanks!

The uiTableFilter plugin doesn't support what you're trying to do. A quick look at the source reveals this:
elems.each(function(){
var elem = jQuery(this);
jQuery.uiTableFilter.has_words(getText(elem), words, false)
? matches(elem)
: noMatch(elem);
});
and that expands to (essentially) this:
elems.each(function(){
var elem = jQuery(this);
jQuery.uiTableFilter.has_words(getText(elem), words, false)
? elem.show()
: elem.hide();
});
So all it does is spin through all the rows, .show() those that match, and .hide() those that don't; uiTableSorter doesn't pay attention to the current shown/hidden state of the rows and there's no way to tell it to filter on multiple columns.
If you really need your desired functionality then you can modify the plugin's behavior (the code is pretty small and simple) or just write your own. Here's a stripped down and simplified version that supports multiple filters and is a more conventional jQuery plugin than uiTableFilter:
(function($) {
$.fn.multiFilter = function(filters) {
var $table = $(this);
return $table.find('tbody > tr').each(function() {
var tr = $(this);
// Make it an array to avoid special cases later.
if(!$.isArray(filters))
filters = [ filters ];
howMany = 0;
for(i = 0, f = filters[0]; i < filters.length; f = filters[++i]) {
var index = 0;
$table.find('thead > tr > th').each(function(i) {
if($(this).text() == f.column) {
index = i;
return false;
}
});
var text = tr.find('td:eq(' + index + ')').text();
if(text.toLowerCase().indexOf(f.word.toLowerCase()) != -1)
++howMany;
}
if(howMany == filters.length)
tr.show();
else
tr.hide();
});
};
})(jQuery);
I'll leave error handling and performance as an exercise for the reader, this is just an illustrative example and I wouldn't want to get in the way of your learning. You could wire it up something like this:
$('#type').keyup(function() {
$('#leeLooDallas').multiFilter({ column: 'petType', word: this.value });
});
$('#color').keyup(function() {
$('#leeLooDallas').multiFilter([
{ column: 'petType', word: $('#type').val() },
{ column: 'petColor', word: this.value }
]);
});
And here's a live example (which assumes that you're going to enter something in "type" before "color"): http://jsfiddle.net/ambiguous/hdFDt/1/

Related

Multiple filtering and sort by in Shopify liquid

I am trying to merge storefront filtering and sorting in my custom theme collections page in Shopify.
Both things work, but the 'sort_by' parameters are overwriting the filtering ones when these are multiple.
i.e of how the URL should look once filtering with two parameters (sizes XXS and XL) and sorting by ascending price:
../collections/new-arrivals?filter.v.option.size=XXS&filter.v.option.size=XL&sort_by=price-ascending
But this is what happens when sorting:
../collections/new-arrivals?filter.v.option.size=XXS&sort_by=price-ascending
Second filtering parameter gets overwritten by the sorting one.
Pasting below my code for the JS piece that triggers the sorting behaviour.
// sortby
$(function() {
Shopify.queryParams = {};
if(location.search.length) {
for(var aKeyValue, i = 0, aCouples = location.search.substr(1).split('&'); i < aCouples.length; i++) {
aKeyValue = aCouples[i].split('=');
if (aKeyValue.length > 1) {
Shopify.queryParams[decodeURIComponent(aKeyValue[0])] = decodeURIComponent(aKeyValue[1]);
}
}
}
document.querySelector('.sort-by').addEventListener('change', function(e) {
var value = e.currentTarget.value;
Shopify.queryParams.sort_by = value;
location.search = new URLSearchParams(Shopify.queryParams).toString();
});
})
Has someone ever tried to achieve something like this?
I would appreciate any help.
Thanks in advance,

Search datatables columns with AND condition

I have a datatable and the 5th column of this table contains several labels. I also have a separate labels list with checkboxes, where user can select multiple labels and filter the table. I found the following way to filter the table:
table.column(5).search('value1|value2', true, false).draw();
This returns all the rows, that contain value1 OR value2, but I need to return the rows that contain both, value1 AND value2, but I could not find anything about this. I tried something like this as an experiment, but it did not work:
table.column(5).search('value1&value2', true, false).draw();
How do I search the datatable with an AND condition?
As andrewJames suggested in the comment, I used the Datatables search plug-in and created a custom filter function:
$('.labels-filter-button').unbind().click(function(){
$.fn.dataTable.ext.search.push(function (settings, data, dataIndex) {
let selectedLabels = $('#labelsFilterSelector').val();
let content = data[5];
let rowIncludes = true;
for (var i = 0; i < selectedLabels.length; i++) {
if (content.indexOf(selectedLabels[i]) == -1){
rowIncludes = false;
}
}
return rowIncludes;
});
table.draw();
$.fn.dataTable.ext.search.pop();
});
Works like a charm on any number of inputs.

How to filter record by custom value from any dimension in dc.js?

How to remove custom records from any dimension. In the below case how do I filter only category 'S' and allow rest of them in dimension ?
Example
let data = [
{category:'A',value:10},
{category:'B',value:11},
{category:'S',value:12},
{category:'A',value:14},
{category:'B',value:12},
]
let ndx = crossfilter(data);
let dim= ndx.dimension(function(d){
if(d.category != "S") return d.category;
})
This above code runs into loop and the application crashes. I don't want to create separate data for this dimension rather link it with other cross filters.
I guess its pretty simple, I did little research after posting the question.
Just manipulate the group parameter being passed to the chart. The code goes something like this.
Since I am trying to remove the value by key lets first write a function for further uses as well.
function removeByKey(source_group, value) {
return {
all: function() {
return source_group.all().filter(function(d) {
return d.key != value;
});
}
};
}
Once this is done the place where you call the group method for the charts call this method. The first parameter of removeByKey method is the group itself the second is the key value which is supposed to be removed from the chart.
chart
.dimension(dimension_data)
.group(removeByKey(dimension_data_group, 'S'))
Thanks :)

Dexie.js - ordering with more than one index

I am using dexie.js to interface with IndexedDB. I am wondering if it is possible to orderby or sortby using more than one index at once (eg. db.people.orderBy( index1, desc : index2, asc )...
If it is possible, what is the correct syntax?
Either use compound indexes, or use Collection.and().
If you can live with only targeting Chrome, Firefox or Opera, you can use compound indexes. If it must work on Safari, IndexedDBShim, Edge or IE, you cannot use compound indexes today. There's a shim that enables it for IE/Edge though, but it is still in beta, so I would recommend to instead use Collection.and() for those cases.
Let' say you have a form where users can fill in various attributes of friends:
<form>
<input name="name"/>
<input name="age"/>
<input name="shoeSize" />
</form>
Using Collection.and()
First, pick the most probably index to start your search on. In this case, "name" would be a perfect index that wouldn't match so many items, while age or shoeSize would probably match more friends.
Schema:
db.version(X).stores({
friends: "id, name, age, shoeSize"
});
Query:
function prepareQuery () {
// Pick a good index. The picked index will filter out with IndexedDB's built-in keyrange
var query;
if (form.name.value) {
query = db.friends.where('name').equals(form.name.value);
} else if (form.age.value) {
query = db.friends.where('age').equals(parseInt(form.age.value));
} else if (form.shoeSize.value) {
query = db.friends.where('shoeSize').equals(parseInt(form.shoeSize.value));
} else {
query = db.friends.toCollection();
}
// Then manually filter the result. May filter a field that the DB has already filtered out,
// but the time that takes is negligible.
return query.and (function (friend) {
return (
(!form.name.value || friend.name === form.name.value) &&
(!form.age.value || friend.age == form.age.value) &&
(!form.shoeSize.value || friend.shoeSize == form.shoeSize.value));
});
}
// Run the query:
form.onsubmit = function () {
prepareQuery() // Returns a Collection
.limit(25) // Optionally add a limit onto the Collection
.toArray(function (result) { // Execute query
alert (JSON.stringify(result, null, 4));
})
.catch (function (e) {
alert ("Oops: " + e);
});
}
Using compound indexes
As written above, compound indexes code will only work on mozilla- and chromium based browsers.
db.version(x).stores({
friends: "id, name, age, shoeSize," +
"[name+age+shoeSize]," +
"[name+shoeSize]," +
"[name+age]," +
"[age+shoeSize]"
});
The prepareQuery() function when using compound indexes:
function prepareQuery() {
var indexes = []; // Array of Array[index, key]
if (form.name.value)
indexes.push(["name", form.name.value]);
if (form.age.value)
indexes.push(["age", parseInt(form.age.value)]);
if (form.shoeSize.value)
indexes.push(["shoeSize", parseInt(form.shoeSize.value)]);
var index = indexes.map(x => x[0]).join('+'),
keys = indexes.map(x => x[1]);
if (indexes.length === 0) {
// No field filled in. Return unfiltered Collection
return db.friends.toCollection();
} else if (indexes.length === 1) {
// Single field filled in. Use simple index:
return db.friends.where(index).equals(keys[0]);
} else {
// Multiple fields filled in. Use compound index:
return db.friends.where("[" + index + "]").equals(keys);
}
}
// Run the query:
form.onsubmit = function () {
prepareQuery() // Returns a Collection
.limit(25) // Optionally add a limit onto the Collection
.toArray(function (result) { // Execute query
alert (JSON.stringify(result, null, 4));
})
.catch (function (e) {
alert ("Oops: " + e);
});
}
Using arrow functions here to make it more readable. Also, you're targeting chromium or firefox and they support it already.

jqGrid drag and drop headings for grouping .... Group Name

I have setup drag and drop headings to group by the relevant column from jQgrid Grouping Drag and Drop
It works great however I am trying to display the column name before the value i.e.
Client : Test data data
Client : Test2 data data
I've been going around in circles if any one could help.
if i take the same code used for the dynamic group by which should be the (column Name)
I end up with The Column data not the column name.
$('#' + gridId).jqGrid('groupingGroupBy', getheader());
function getheader() {
var header = $('#groups ol li:not(.placeholder)').map(function () {
return $(this).attr('data-column');
}).get();
return header;
}
if i use the same function in group text I get data not the column name.
I've come from C# and I am very new to jQuery.
If any one could help it would be greatly appreciated.
Kind Regards,
Ryan
First of all the updated demo provides the solution of your problem:
Another demo contains simplified demo which demonstrates just how one could display the grouping header in the form Column Header: Column data in the grouping header instead of Column data used as default.
The main idea of the solution is the usage of formatDisplayField property of groupingView which I suggested originally in the answer. The current version of jqGrid support the option. If one would use for example the options
grouping: true,
groupingView: {
groupField: ["name", "invdate"],
groupColumnShow: [false, false],
formatDisplayField: [
customFormatDisplayField,
customFormatDisplayField
]
}
where customFormatDisplayField callback function are defined as
var customFormatDisplayField = function (displayValue, value, colModel) {
return colModel.name + ": " + displayValue;
}
will display almost the results which you need, but it will uses name property of colModel instead of the corresponding name from colNames. To makes the final solution one use another implementation of customFormatDisplayField:
var getColumnHeaderByName = function (colName) {
var $self = $(this),
colNames = $self.jqGrid("getGridParam", "colNames"),
colModel = $self.jqGrid("getGridParam", "colModel"),
cColumns = colModel.length,
iCol;
for (iCol = 0; iCol < cColumns; iCol++) {
if (colModel[iCol].name === colName) {
return colNames[iCol];
}
}
},
customFormatDisplayField = function (displayValue, value, colModel, index, grp) {
return getColumnHeaderByName.call(this, colModel.name) + ": " + displayValue;
};

Resources