Home > Software design >  How to read a csv file using jQuery and html and check a condition
How to read a csv file using jQuery and html and check a condition

Time:01-07

I want to read a csv file using jQuery and html and see if a condition applies to the cell. So basically I have a csv file with transactions and I want to check if that transaction matches with my keyword and then the program would give it a certain id number

This is all I got up to:

    <div >
      <input type="file"  id="csv" aria-describedby="file" aria-label="Upload">
      <button  type="button" id="upload">Upload</button>
    </div>
    <script>
      $(document).ready(function(){
      $("#upload").clicked(function(){

        
      })
    });
  });

CodePudding user response:

function handleFileSelect() {
    // get the file input element
    var input = document.getElementById('fileInput');

    // get the selected file
    var file = input.files[0];

    // read the file
    var reader = new FileReader();
    reader.readAsText(file);

    // when the file is read, process it
    reader.onload = function(event) {
      var csv = event.target.result;
      processData(csv);
    }
  }
//Call the handleFileSelect function when the file input element changes:


//Implement the processData function to parse the CSV data and do something with it:



  function processData(csv) {
    // split the CSV data into rows
    var rows = csv.split('\n');

    // loop over the rows
    for (var i = 0; i < rows.length; i  ) {
      // split the row into columns
      var cols = rows[i].split(',');

      // do something with the data
      console.log(cols);
      // you can add another loop here and apply the condition on desired column
    }
  }
<form>
  <input type="file" id="fileInput" accept=".csv" onchange="handleFileSelect()" />
</form>

That's it! Now, when a user selects a CSV file, it will be read and the data will be processed. You can customize the processData function to do whatever you want with the data, such as displaying it in a table or chart.

CodePudding user response:

In case you want to use a CSV datasource that is available to you online and use it as a basis for further data checks then you can load it asynchronously with jQuery in the following way:

var holidays; // global array of objects (available only after asynchronous loading has finished!)
$.get("https://date.nager.at/PublicHoliday/Country/DE/2023/CSV").done(function(csv){
 holidays=$.csv.toObjects(csv);
 console.log(holidays);
})
<script src="https://code.jquery.com/jquery-3.6.3.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-csv/1.0.21/jquery.csv.min.js"></script>

  • Related