I have file.csv like this:
Name,Gender //header
John,M
Luke,M
Jessy,F
I want to count total M and F with javascript so I have tried this:
<script type="text/javascript">
$(function () {
$("#upload").bind("click", function () {
var regex = /^([a-zA-Z0-9\s_\\.\-:])+(.csv|.txt)$/;
var F = 0;
var M = 0;
if (regex.test($("#fileUpload").val().toLowerCase())) {
if (typeof (FileReader) != "undefined") {
var reader = new FileReader();
reader.onload = function (e) {
var table = $("<table />");
var rows = e.target.result.split("\n");
for (var i = 0; i < rows.length; i++) {
var row = $("<tr />");
var cells = rows[i].split(",");
var gender = cells[1];
if (gender === "F"){
F++;
}else{
M++;
}
for (var j = 0; j < cells.length; j++) {
var cell = $("<td />");
cell.html(cells[j]);
row.append(cell);
}
table.append(row);
}
$("#dvCSV").html('');
$("#dvCSV").append(table);
window.alert(pos);
}
reader.readAsText($("#fileUpload")[0].files[0]);
}
});
});
</script>
But var F & M not increased (just increased to 1 and didn't increase anymore) , can you help me to solve this problem? :(
\r\n(CR+LF) rather than just\n(LF). In this case, what you get isM\randF\r. Only the last row might be processed correctly if it's not followed by a carriage return.