Friday, August 3, 2018

how do you reorder rows in a table based on a TR attribute using JQuery

A table with rows similar to the following.
These rows get updated from time to time via jquery calls.

 Using jquery,
 how would I construct a function that reorders these table rows based on the CSSclass value putting the highestCSSclass value rows at the top and the lowest CSSclass  value rows at the bottom? There could be up to n rows in the table.

<table id="dtmarksList">
<tbody>
<tr>
 <th >S.NO</th><th >Name</th><th >Marks</th><th >Subject</th>
</tr>
<tr>
 <td> 1</td>
<td> test</td>
<input name="txtmarks1" type="text"  id="txtmarks1" Class="markvalue">
<td> Science</td>
</tr>
</tr>
 <td> 2</td>
<td> test2</td>
<input name="txtmarks2" type="text"  id="txtmarks2" Class="markvalue">
<td> Maths</td>
</tr>

</tr>
 <td> 3</td>
<td> test3</td>
<input name="txtmarks3" type="text"  id="txtmarks3" Class="markvalue">
<td> Maths</td>
</tr>
......
.....
......
</tr>
 <td> n</td>
<td> testn</td>
<input name="txtmarksn" type="text"  id="txtmarksn" Class="markvalue">
<td> Maths</td>
</tr>
</tbody>
</table>


Method: 


$("input[type=text].markvalue").blur(function () {

var $table=$('#dtmarksList');

var rows = $table.find('tr').get();
rows.sort(function(a, b) {
var txtmark=$(a).find('.markvalue').val();
if (txtmark) return  0;    /* Small Value for sorting */ 
return 1;     /* High value for sorting */
});

$table.children('tbody').html(rows);

/*
$.each(rows, function(index, row) {
$table.children('tbody').append(row);
});
*/

});

Method 2:

            $("#dtmarksList tr input[type=text].markvalue").each(function (i) {
                if ($(this).val() != '')
                {
                  $($("#dtmarksList").find('tr:first')).after($("#" + $(this).attr("id")).closest('tr'));
                } 
            });



No comments:

Change default Port on Next.js app

 If any other app or process is running on port 3000 , you will get this error in your terminal Port 3000 is already in use. error Command f...