This is copied directly from Stackoverflow as I was suggested to post it here.
I have the below code, which does work fine but I find it quite big and had hoped there was a cleaner/smaller "toggle" function or alike which I could use but it seems to be related to visibility only - and I want to set a variable (for later usage).
Can this below be optimized, if I want a toggle function which should be used to sort a column (and get the value in to a variable)?
<table>
<thead>
<tr>
<td>Col 1</td>
<td>Col 2</td>
<td>Col 3</td>
</tr>
</thead>
<tbody>
<tr>
<td>A</td>
<td>B</td>
<td>C</td>
</tr>
<tr>
<td>B</td>
<td>C</td>
<td>A</td>
</tr>
</tbody>
</table>
And the jQuery stuff:
var column;
var order;
$('thead th').click(function () {
// Get the current column clicked
var thisColumn = $(this).text();
// Check if the column has changed
if(thisColumn == column) {
// column has not changed
if(order == "ascending") {
order = "descending";
} else {
order = "ascending";
}
} else {
// column has changed
column = thisColumn;
order = "descending";
}
// Replace text in DIV
$("div").text("column=["+column+"], order=["+order+"]");
// future code will use the sort order to get database
// stuff with Ajax
});
Check JSFiddle code here, http://jsfiddle.net/Psz5K/
th
elements in your HTML code – rink.attendant.6 Aug 21 '13 at 17:20th
is in the Fiddle demo (I must have copied an old code snippet). – DHS Aug 22 '13 at 8:39