How do I create a simple sorting function for this. I know there is plugin like tablesorter. But it doesn't sort it from a dropdown list. Or is the plugin can be modified so that it can sort from a dropdown list. Thank you in advance.
HTML:
<form action="#" method="post">
<input type="text" id="UserID" name="UserID" readonly="readonly">
<input type="text" id="UserName" name="UserName" placeholder="Name">
<input type="text" id="UserOccupation" name="UserOccupation" placeholder="Occupation">
<button type="button" name="button">Add</button><br>
</form>
Sort By:
<select>
<option>ID</option>
<option>Name</option>
<option>Occupation</option>
</select>
<table id="table" class="tablesorter">
<thead>
<tr >
<th>ID</th>
<th>Name</th>
<th>Occupation</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
Javascript:
$(document).ready(function() {
//Set id field to 1
var id = $('#UserID');
id.val("1");
//Add 1 to the id in textbox
function incID(){
var str = id.val();
var int = parseInt(str);
var idVal = int + 1;
id.val(idVal.toString());
}
//When button clicked
$('button').on('click', function(){
//create a new object
var obj = new Object();
//pass value dynamically from input box
obj.id = $('#UserID').val();
obj.name = $('#UserName').val();
obj.occupation = $("#UserOccupation").val();
//display data to the table
var addrow = "<tr><td>" + obj.id + "</td><td>" + obj.name + "</td><td>"+ obj.occupation +"</td></tr>";
$("table tbody").append(addrow);
//Add 1 to id field
incID();
});
});
Sorting the table is fairly easy to do yourself, all you'd have to do is sort the rows using javascript's sort method (http://www.w3schools.com/jsref/jsref_sort.asp) and re-adding the rows to the table.
You could create sorting methods for different data-types like:
(working example at https://jsfiddle.net/kg000ta7/)
However, if you plan to have a lot of rows or columns in your table, a plugin like tablesorter will probably perform better.
According to the documentation you are able to manually sort tablesorter by triggering the 'sorton' event: http://tablesorter.com/docs/example-trigger-sort.html