2
votes

I am parsing an XML file into a table and want to use the jquery tablesorter. Now that I've got the error to go away for tablesorter not existing, my data is populating in the table but the headers are not able to be sorted. Any ideas? Code is listed below for JS and HTML.

HTML:

<html> 
<head> 
    <title>Read XML</title> 
    <script type="text/javascript" src="jquery-1.7.1.js"></script>  
    <script type="text/javascript" src="jquery.tablesorter.js"></script> 
    <script type="text/javascript" src="custom.js"></script> 
</head> 
<body> 
    <table id="table" border="1"> 
        <thead> 
            <tr> 
                <th>Item #</th> 
                <th>Shape</th> 
                <th>Weight</th> 
                <th>Color</th> 
                <th>Clarity</th> 
                <th>Price($)</th> 
           </tr> 
        </thead> 
        <tbody> 
        </tbody> 
    </table> 
</body> 
</html> 

JS:

$(document).ready(function() { 
$("#table").tablesorter(); 
$.ajax({ 
     type: "GET", 
     url: "tutorial.xml", 
     dataType: "xml", 
     success: parseXml 
}); 
$("#table").trigger("update"); 
}); 

function parseXml(xml) 
{ 
    $(xml).find("diamond").each(function() 
    { 
        $("#table tbody").after("<tr><td>" + $(this).find("id").text() +  
        "</td><td>" + $(this).find("shape").text() + "</td><td>" + $(this).find("weight").text() +  
        "</td><td>" + $(this).find("color").text() + "</td><td>" + $(this).find("clarity").text() +  
        "</td><td>" + $(this).find("price").text() + "</td></tr>"); 
    }); 
} 
2
Does the two typos fixed your code? - rekire
they fixed the problem from my last question of the tablesorter not being a function. - Brandon

2 Answers

2
votes

You need $("#table").trigger("update"); at the end of parseXml to tell tablesorter that the table has been updated. It doesn't help if it is run before the ajaxRequest has returned.

1
votes

Move this line:

$("#table").trigger("update");

to the end of the parseXML method, and change .after to .append

function parseXml(xml) 
{ 
    $(xml).find("diamond").each(function() 
    { 
        $("#table tbody").append("<tr><td>" + $(this).find("id").text() +  
        "</td><td>" + $(this).find("shape").text() + "</td><td>" + $(this).find("weight").text() +  
        "</td><td>" + $(this).find("color").text() + "</td><td>" + $(this).find("clarity").text() +  
        "</td><td>" + $(this).find("price").text() + "</td></tr>"); 
    }); 
    $("#table").trigger("update");
}