TechDinoKing TechDinoKing - 2 months ago 13
Ajax Question

Jquery - appending each element

My Code:

This is my CSV file:

Item, Quantity, Price;
LED, 100, $10;
PIR, 1, $5;
DS18B20, 10, $5;


This is my jquery file:

$(document).ready(function() {
$.ajax({
url: "data.csv",
success: function(result) {
var data = result;
var arr = data.split(";");
var len = arr.length - 1;
var a = 0;
var b = 0;
while (a < len) {
var orr = arr[a].split(",");
var err = orr.length;
b = 0;
while (b < err) {
if (a == 0) {
$("#table").find('table')
.append($('<tr>')
.append($('<th>' + orr[b] + '</th>'))
);
b = b + 1;
} else if (a > 0) {
$("#table").find('table')
.append($('<tr>')
.append($('<td>' + orr[b] + '</td>'))
);
b = b + 1;
};
};
a = a + 1;
};
}
});
});


This code puts every element into a TR tag and i want it to put all the elements in one line in a TR tag.

This is my HTML file:

<!DOCTYPE html>
<html>
<head>
<title>tables</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script src="myjquery.js">
</head>
<body>
<div id="table">
<table>
</table>
</div>
</body>
</html>


(this text is to stop the popup stopping me from posting because of too much code)

Answer

var csv = 'Item, Quantity, Price;' +
          'LED, 100, $10;' +
          'PIR, 1, $5;' +
          'DS18B20, 10, $5;';

$(document).ready(function() {
  var arrCsv = csv.split(';');
  var result = '';
  
  $.each(arrCsv, function(key, val) {
    if (val.trim() !== '') {
      var arrCols = val.split(',');
    
      result += '<tr>';
    
      $.each(arrCols, function(idx, value){
        result += (key == 0 ? '<th>' : '<td>') + value + (key == 0 ? '</th>' : '</td>');
      });
    
      result += '</tr>';
    }
  });
  
  $('table').append(result);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<table border="1" width="100%">
</table>