Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding a row and sorting table using JavaScript

I am running into a very small issue which has taken more than two hours.

What I want is to insert a row in an HTML table and then sort it in ascending order. I've looked at this answer and thought that I can get this simple task working, but in vein.

Here is my little form and table:

Name: <input type="text" name="name" id="name"><br>
Status: <input type="text" name="status" id="status">><br>
<button onclick="myFunction(document.getElementsByName('name')[0].value,document.getElementsByName('status')[0].value)">Click</button><br><br>
<table id="myTable">
    <thead>
        <tr>
            <th>Name</th>
            <th>Status</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>Doe, John</td>
            <td>Approved</td>
        </tr>
        <tr>
            <td>aaa, John</td>
            <td>Approved</td>
        </tr>
    </tbody>
</table>

My inline JavaScript function looks like this:

function myFunction(name, status) {
    var table = document.getElementById('myTable').getElementsByTagName('tbody')[0];
    var row = table.insertRow(0);
    var cell1 = row.insertCell(0);
    var cell2 = row.insertCell(1);
    cell1.innerHTML = name;
    cell2.innerHTML = status;

    // The following code should sort the table.
    var tbody = $('#mytable').find('tbody');
    tbody.find('tr').sort(function (a, b) {
        return $('td:first', a).text().localeCompare($('td:first', b).text());
    }).appendTo(tbody);
}

Please note that adding a row to the table works fine, it just adds it to the top.

There are no console errors. The code which (apparently) should sort the table does not do anything. I've the subset of my HTML here on Fiddle, and yes that works fine.


I know about jQuery tablesorter plugin but do not need to use it.

like image 364
Farhan Avatar asked Jul 28 '15 20:07

Farhan


1 Answers

This selector:

$('#mytable')

...is incorrect. Your table's ID is myTable, and IDs are case-sensitive. Here's a working version of your code with that fix.

like image 85
Jacob Avatar answered Sep 24 '22 01:09

Jacob