Jquery文本字段排序
问题描述:
Is it possible to sort the text fields using jquery? I want to sort the values in the text field. I couldn't use grids. I need to do it in Jquery.
<table width="50%" border="0">
<tr>
<td><label>
<input name="textfield" type="text" value="5">
</label></td>
</tr>
<tr>
<td><label>
<input name="textfield" type="text" value="3">
</label></td>
</tr>
<tr>
<td><label>
<input name="textfield" type="text" value="6">
</label></td>
</tr>
<tr>
<td><label>
<input name="textfield" type="text" value="1">
</label></td>
</tr>
<tr>
<td><label>
<input name="textfield" type="text" value="9">
</label></td>
</tr>
<tr>
<td><label>
<input name="textfield" type="text" value="8">
</label></td>
</tr>
</table>
I want to sort the text fields as 1,3,5,6,8,9 (ASC order). I couldn't find the solution. Please do the needful. Thanks
答
var mylist = $('table');
var listitems = mylist.find('input[type=text]');
listitems.sort(function(a, b) {
var compA = $(a).val();
var compB = $(b).val();
return (compA < compB) ? -1 : (compA > compB) ? 1 : 0;
})
$.each(listitems, function(idx, itm) { mylist.append(itm); });
答
Give them ids then iterate through the DOM using the each()
function, whilst using a sorting algorithm.