How can I sort columns having input elements?

kender picture kender · Dec 16, 2009 · Viewed 18.6k times · Source

I have a table like this:

|   Update   |   Name  |  Code      | modification date |
|            |   name1 | code1      | 2009-12-09        |
|            |   name2 | otehercode | 2007-09-30        | 

Where the Update column contains checkboxes <input type='checkbox' />.

The checkbox initial state is determined before rendering the table, but after the rows are fetched from database (it's based on set of conditions, on the server-side).

The checkbox can be checked by default, unchecked by default or disabled (disabled='disabled' as input attribute).

I'm using jQuery's Tablesorter to sort my tables. And I'd like to be able to sort by the column containing the checkboxes. How is it possible (I could pass some additional attributes to my input element maybe, if it would help...)?

Should I write my own parser to handle that?

Answer

salgiza picture salgiza · Dec 16, 2009

Add a hidden span just before the input, and include in it some text (that will be used to sort the column). Something like:

<td>
    <span class="hidden">1</span>
    <input type="checkbox" name="x" value="y">
</td>

If needed, you can attach an event to the checkbox so that it modifies the content of the previous sibling (the span) when checked/unchecked:

$(document).ready(function() {

    $('#tableid input').click(function() {
         var order = this.checked ? '1' : '0';
         $(this).prev().html(order);
    })

})

Note: I haven't checked the code, so it might have errors.