For my internship I have to make a filter for a table which has to show only the rows that are between the values you give it.
I used jQuery UI for the range slider
and I have a normal HTML table.
I cant get it to work and I’ve tried many different things. Here’s my code:
$(function() { $( "#slider-range" ).slider({ range: true, min: 0, max: 500, values: [ 75, 300 ], slide: function( event, ui ) { $( "#amount" ).val( "$" + ui.values[ 0 ] + " - $" + ui.values[ 1 ] ); $( "#amount" ).val( "$" + $( "#slider-range" ).slider( "values", 0 ) + " - $" + $( "#slider-range" ).slider( "values", 1 ) ); $("#ADC_DAC").find("td:nth-child(0)").filter(function () { return parseInt($(this).text()) < $( "#slider-range" ).slider( "values", 0 ); }).parent().hide(); $("#ADC_DAC").find("td:nth-child(0)").filter(function () { return parseInt($(this).text()) > $( "#slider-range" ).slider( "values", 1 ); }).parent().hide(); } }); });
The slider has the ID slider-range
and the table ID ADC_DAC
.
My table is made up like this:
<table id="ADC_DAC"> <tr> <td>h1</td> <td>h2</td> <td>h3</td> </tr> <tr> <td>23</td> <td>test</td> <td>test2</td> </tr> </table>
But then with way more rows and with values between 0 and 500 for the first row (which needs filtering)
Advertisement
Answer
You were on the right track by trying to change the table properties in the slide: function() {}
.
However, the code in the function makes use of find
‘s and other unfavourable selectors.
The easiest way would be to simply select the table and go over each row and column like so:
var table = document.getElementById("theTable"); for (var i = 1, row; row = table.rows[i]; i++) { //iterate through rows (we SKIP the first row: counter starts at 1!) for (var j = 0, col; col = row.cells[j]; j++) { //iterate through columns: if first column not in range: HIDE, else SHOW if (j == 0) { // if first column if ($(col).html() >= ui.values[ 0 ] && $(col).html() <= ui.values[ 1 ]) { // if in interval $(row).show(); } else { $(row).hide(); } } } }
That should do what you want. This solution is much easier than yours because you don’t have to deal with the .parent
and .children
selectors. Especially for 2D structures like tables, for loops
are often easier to grasp and maintain a nice level of readability. However, it might not be the shortest code.
Here is the working jsFiddle demo: