javascript - Appending to a list -
i'm trying append data csv file unordered html list. csv file contains 2 different types of data list.. single , grouped show below:
test group name a,test link name 1,test url 1 test group name a,test link name 2,test url 2 test group name b,test link name 3,test url 3 test group name b,test link name 4,test url 4 test link name 5,test url 5 test link name 6,test url 6 the end result needs below:
test group name test link name 1,test url 1 test link name 2,test url 2 test group name b test link name 3,test url 3 test link name 4,test url 4 test link name 5,test url 5 test link name 6,test url 6 i can append single links fine getting grouped links out of csv , separate <ul> id="" each proving rather tricky. think i'd need add each group item own array or object , construct html can't think how it. code i've created far looks below:
var htmlmenu = ''; $.get(csvfilefolder, function( csvfile ) { var data = $.csv.toarrays(csvfile); for(var row in data) { if (data[row].length > 2){ htmlmenu += '<li><a href="#">'+data[row][0]+'</a><ul><li><a href="'+data[row][1]+'" target="_blank">'+data[row][2]+'</a></li></ul></li>' //i need able add items <ul> group names }else{ htmlmenu += '<li><a href="'+data[row][1]+'" target="_blank">'+data[row][0]+'</a></li>'; //this works fine } } $('#usefullinks').append(htmlmenu); }); anyone able help?
thanks
ben
it seems want group (name, test) pairs in sublists when group specified, or add main list if not specified. should work:
// csv set dummy string illustrate var csv = 'test group name a,test link name 1,test url 1\ntest group name a,test link name 2,test url 2\ntest group name b, test link name 3,test url 3\ntest group name b,test link name 4,test url 4\ntest link name 5,test url 5\ntest link name 6,test url 6'; var lines = csv.split('\n'); // initialize main list var mainul = $('<ul></ul>'); var group; var id = 0; (var = 0; < lines.length; i++) { // split lines comma ommiting space row = lines[i].split(/\s*,\s*/g); if (row.length === 3) { //if belonging group if (row[0] !== group) { group = row[0]; // create new sub list unique id var subul = $('<ul id="ul' + id + '"></ul>'); // add sublist new list item on main list var li = $('<li><h6>' + row[0] + '</h6></li>'); li.append(subul); li.appendto(mainul); id += 1; // increment id after each subgroup access each group's ul sequencially // <ul id="ul0">, <ul id="ul1">... ul preix works // older versions of html (where ids cannot start number) } // add items group $('<li>' + row[1] + ',' + row[2] + '</li>').appendto(subul); } else { // add li without sub list if // not belonging group var li = $('<li></li>'); li.text(row[0] + ',' + row[1]); mainul.append(li); } }; // add main list body $('body').append(mainul);
Comments
Post a Comment