javascript - convert getJson to table and make sortable WITHOUT plugins -
ok, close here. sort function works on regular html table, when try load table using getjson not work, , hoping due lack of knowledge in realm of jquery , js. not headed down wrong path completely. here code. in advance!
<!doctype html> <html lang="en"> <head> <meta charset="utf-8" /> </head> <body> <div id="cattable"></div> <script src="http://code.jquery.com/jquery-1.7.1.min.js"></script> <script type="text/javascript"> var tableidvalue = "indextable"; var tablelastsortedcolumn = -1; function sorttable() { var sortcolumn = parseint(arguments[0]); var type = arguments.length > 1 ? arguments[1] : 't'; var dateformat = arguments.length > 2 ? arguments[2] : ''; var table = document.getelementbyid(tableidvalue); var tbody = table.getelementsbytagname("tbody")[0]; var rows = tbody.getelementsbytagname("tr"); var arrayofrows = new array(); type = type.touppercase(); dateformat = dateformat.tolowercase(); for(var i=0, len=rows.length; i<len; i++) { arrayofrows[i] = new object; arrayofrows[i].oldindex = i; var celltext = rows[i].getelementsbytagname("td")[sortcolumn].innerhtml.replace(/<[^>]*>/g,""); if( type=='d' ) { arrayofrows[i].value = getdatesortingkey(dateformat,celltext); } else { var re = type=="n" ? /[^\.\-\+\d]/g : /[^a-za-z0-9]/g; arrayofrows[i].value = celltext.replace(re,"").substr(0,25).tolowercase(); } } if (sortcolumn == tablelastsortedcolumn) { arrayofrows.reverse(); } else { tablelastsortedcolumn = sortcolumn; switch(type) { case "n" : arrayofrows.sort(comparerowofnumbers); break; case "d" : arrayofrows.sort(comparerowofnumbers); break; default : arrayofrows.sort(comparerowoftext); } } var newtablebody = document.createelement("tbody"); for(var i=0, len=arrayofrows.length; i<len; i++) { newtablebody.appendchild(rows[arrayofrows[i].oldindex].clonenode(true)); } table.replacechild(newtablebody,tbody); } // function sorttable() function comparerowoftext(a,b) { var aval = a.value; var bval = b.value; return( aval == bval ? 0 : (aval > bval ? 1 : -1) ); } $.getjson('cats.json', function(cats) { var output='<table id="indextable" border="1" cellpadding="10" cellspacing="0" style="border-collapse:collapse;">'; output+="<thead>" output+="<tr>"; //output+="<th> headshot </th>"; output+='<th><a href=' + "javascript:sorttable(1,'t');" + '>breed</a></th>'; output+='<th><a href=' + "javascript:sorttable(1,'t');" + '>country</a></th>'; output+='<th><a href=' + "javascript:sorttable(1,'t');" + '>coffeepreference</a></th>'; output+="</tr>"; output+="</thead>" (var in cats) { output+="<tbody>" output+="<tr>"; //output+="<td><img src='" + cats[i].picture+"' alt='cat picture'></td>" output+="<td>" + cats[i].breed + "</td>" output+="<td>" + cats[i].country + "</td>" output+="<td>" + cats[i].coffeepreference + "</td>" output+="</tr>"; output+="</tbody>" } output+="</table>"; document.getelementbyid("cattable").innerhtml=output; }); </script> </body> </html>
Comments
Post a Comment