问题
1) The code below will sort the input boxes as they are when loaded on the page load, but if I try and edit any of the <input>s then try sort the column again then it sorts by the original value and not the new value, can you help fix this?
2) If I type new numbers in the <input> then click on the column header to sort then my inputs blur event will not fire, why and do you know how to fix this?
<table id="myTable" class="tablesorter">
<thead>
<tr>
<th>Last Name</th>
<th>Amounts</th>
</tr>
</thead>
<tbody>
<tr>
<td>Smith1</td>
<td><input type="text" value="1"/></td>
</tr>
<tr>
<td>Smith2</td>
<td><input type="text" value="2"/></td>
</tr>
<tr>
<td>Smith3</td>
<td><input type="text" value="3"/></td>
</tr>
<tr>
<td>Smith4</td>
<td><input type="text" value="4"/></td>
</tr>
</tbody>
</table>
$(document).ready(function() {
$.tablesorter.addParser({
id: 'input',
is: function(s) {
return false;
},
format: function(s, table, cell) {
return $('input', cell).val();
},
type: 'numeric'
});
$("#myTable").tablesorter({
headers: {
1: {
sorter:'input'
}
}
});
$('input').blur(function(){
alert($(this).val());
});
});
回答1:
The parser is only going to grab the input values on initialization. You'll need to update them whenever an input value changes. That being said, I've always had bad luck using blur on inputs, I think it is better to use keyup to check for changes.
Anyway, I've got a demo of a dynamic input parser here. It "should" work with the original version of tablesorter, but the resort option won't be available. Otherwise, I know it works with my fork of tablesorter.
// add parser that dynamically updates input values
$.tablesorter.addParser({
id: 'inputs',
is: function(s) {
return false;
},
format: function(s, table, cell) {
var $c = $(cell);
// return 1 for true, 2 for false, so true sorts before false
if (!$c.hasClass('updateInput')) {
$c
.addClass('updateInput')
.bind('keyup', function() {
$(table).trigger('updateCell', [cell, false]); // false to prevent resort
});
}
return $c.find('input').val();
},
type: 'text'
});
$(function() {
$('table').tablesorter({
widgets: ['zebra'],
headers: {
3: {
sorter: 'inputs'
}
}
});
});
回答2:
Mottie's answer worked for me -- thanks! I didn't like adding a class for the sake of preventing duplicate binds, so I moved the logic outside:
$("#mytable tbody").on("keyup", "input", function(event){
var table = $(this).closest("table");
var cellElement = $(this).closest("td")[0];
table.trigger("updateCell", [cellElement, false]);
});
来源:https://stackoverflow.com/questions/12743935/jquery-tablesorter-wont-sort-correctly-if-new-text-is-typed-in-input