Per completezza, nel caso possa tornare utile a qualcuno, metto qui il codice che ha risolto il problema di @miki92.
Codice:
$(document).ready(function() {
var TableFilter = function(tableObject, fields) {
this.table = tableObject
this.fields = new Array()
this.tableRows = new Array()
this.lastFilteredData = new Array()
this.init = function() {
for(i in fields)
this.addField(fields[i])
tr = new Array()
this.table.find('tr').each(function() {
if($(this).find('th').size() == 0)
tr.push($(this).clone())
})
this.tableRows = tr
}
this.addField = function(field) {
elements = new Array()
this.table.find('tr').each(function() {
$(this).find('td:eq(' + field + ')').each(function() {
txt = $(this).text()
if(elements.indexOf(txt) == -1)
elements.push(txt)
})
})
this.fields.push({
'id': field,
'caption': this.table.find('th:eq(' + field + ')').text().trim(),
'elements': elements
})
}
this.assignSelect = function(fieldCaption, selectObj) {
index = undefined
for(i in this.fields)
if(this.fields[i].caption.toLowerCase() == fieldCaption.toLowerCase())
index = i
for(i in this.fields[index].elements)
selectObj.append('<option value="' + this.fields[index].elements[i] + '">' + this.fields[index].elements[i] + '</option>')
this.fields[index].select = selectObj
selectObj.data('field-id', this.fields[index].id)
}
this.setFilterEvents = function() {
for(i in this.fields) {
this.fields[i].select.on('change', {tClass: this}, function(event) {
if(event.data.tClass.lastFilteredData.length > 0)
source = event.data.tClass.lastFilteredData
else
source = event.data.tClass.tableRows
result = new Array()
for(j in source)
if(source[j].find('td:eq(' + $(this).data('field-id') + ')').text().trim() == $(this).val().trim())
result.push(source[j].clone())
event.data.tClass.updateTable(result)
event.data.tClass.lastFilteredData = result
})
}
}
this.updateTable = function(rows) {
this.table.empty()
this.table.append('<tr><th>data</th><th>compagnia</th><th>destinazione</th><th>orario partenza</th><th>orario stimato</th><th>molo</th><th>annotazioni</th></tr>')
this.table.append(rows)
}
this.resetTable = function() {
this.updateTable(this.tableRows)
this.lastFiltered = new Array()
}
this.init()
}
$('#select-by-destination').append('<option>Destinazione</option>')
$('#select-by-company').append('<option>Compagnia</option>')
// 1 ==> Compagnia
// 2 ==> Destinazione
tabf = new TableFilter($('table:first'), [1, 2])
tabf.assignSelect('Compagnia', $('#select-by-company'))
tabf.assignSelect('Destinazione', $('#select-by-destination'))
tabf.setFilterEvents()
$('#reset-table').on('click', {tf: tabf}, function(event) {
event.data.tf.resetTable()
})
})