Skip to main content

Why is my insertRow method adding blank cells to my table?

I am trying to add the results from a fetch request into a new row in a table. However, When I run the function to do that, the first click adds a blank row instead of adding my desired data. Additionally, the data that I would have liked to add gets added the next time the function is ran. I have no idea what is wrong and I have tried so many things. I believe this problem is causing my other function called "total()" to return an error as the first cell is undefined instead of containing a value.

Here is my javascript:

document.getElementById('getFood').addEventListener('click', getFood);
document.getElementById('getFood').addEventListener('click', total);
/*function getText() {
  $.ajax({
    method: 'GET',
    url:
      'https://api.api-ninjas.com/v1/nutrition?query=' +
      document.getElementById('foodInput'),
    headers: { 'X-Api-Key': 'vrtwcc/pVgAr2o/a4dEyYA==hR1m7lLVdU4ho4hW' },
    contentType: 'application/json',
    success: function (result) {
      console.log(result);
    },
    error: function ajaxError(jqXHR) {
      console.error('Error: ', jqXHR.responseText);
    },
  });
}*/
/*function getFood(foodName) {
  let xhr = new XMLHttpRequest();
  xhr.open(
    'get',
    'https://api.api-ninjas.com/v1/nutrition?query=' + foodName,
    true
  );

  xhr.send();
  xhr.addEventListener('load', function () {
    console.log(xhr.responseText);
  });
}
getFood('fries');*/
function getFood() {
  fetch(
    'https://api.api-ninjas.com/v1/nutrition?query=' +
      `${document.getElementById('foodInput').value}`,
    {
      method: 'GET',
      headers: { 'X-Api-Key': 'vrtwcc/pVgAr2o/a4dEyYA==hR1m7lLVdU4ho4hW' },
      contentType: 'application/json',
    }
  )
    .then((res) => res.json())
    .then((data) => {
      foodQuery = data[0].name;
      calorieQuery = `${data[0].calories} calories`;
    });
  let table = document
    .getElementById('foodTable')
    .getElementsByTagName('tbody')[0];
  let row = table.insertRow(0);
  var cell1 = row.insertCell(0);
  var cell2 = row.insertCell(1);
  cell1.innerHTML = foodQuery;
  cell2.innerHTML = calorieQuery;

  // row.insertCell(0).innerHTML = foodQuery;
  // row.insertCell(1).innerHTML = calorieQuery;
  //document.getElementById('foodInput').value = '';
}
function total() {
  let table = document.getElementById('foodTable');
  let total = 0;
  for (let i = 1; i < table.rows.length; i++) {
    total += Number(table.rows[i].cells[2].innerText);
  }
  document.getElementById('tableTotal').value = total;
}

and here is my HTML:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <script
      src="https://code.jquery.com/jquery-3.6.3.js"
      integrity="sha256-nQLuAZGRRcILA+6dMBOvcRh5Pe310sBpanc6+QBmyVM="
      crossorigin="anonymous"
    ></script>
    <link
      rel="stylesheet"
      href="node_modules/bootstrap/dist/css/bootstrap.css"
    />

    <link rel="stylesheet" href="style.css" />

    <title>Document</title>
  </head>
  <body>
    <div class="container-fluid border border-primary">
      <strong>Jason's Calorie Counter </strong><br />
      <form>
        <div class="form-group" id="">
          <label>Food Selection</label>
          <input
            class="form-control"
            id="foodInput"
            placeholder="Enter food here"
          />
          <small id="foodHelp" class="form-text text-muted"
            >Nutrition data for each food item is scaled to 100g unless a
            quantity is specified
          </small>
          <br />
          <button type="button" class="btn btn-primary" id="getFood">
            Get Food
          </button>
        </div>
      </form>
    </div>
    <table class="table table-bordered" id="foodTable">
      <thead>
        <tr>
          <th scope="col">Food</th>
          <th scope="col">Calories</th>
        </tr>
      </thead>
      <tbody>
        <tr id="rows1">
          <td colspan="2" id="tableTotal">Total</td>
        </tr>
      </tbody>
    </table>

    <script
      src="https://cdn.jsdelivr.net/npm/popper.js@1.14.7/dist/umd/popper.min.js"
      integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1"
      crossorigin="anonymous"
    ></script>
    <script
      src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/js/bootstrap.bundle.min.js"
      integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM"
      crossorigin="anonymous"
    ></script>
    <script src="script.js"></script>
  </body>
</html>

One more important detail: The new row gets added correctly when just adding a string, so it may have to do with the variable or the fetch request. Thank you very much for your time and if there is more information that is missing, please tell me and I will do my best to add it.

I have tried changing the type of data being added, adding them to different parts of the table, changing syntax, etc..

Via Active questions tagged javascript - Stack Overflow https://ift.tt/MSBcpkj

Comments

Popular posts from this blog

How to show number of registered users in Laravel based on usertype?

i'm trying to display data from the database in the admin dashboard i used this: <?php use Illuminate\Support\Facades\DB; $users = DB::table('users')->count(); echo $users; ?> and i have successfully get the correct data from the database but what if i want to display a specific data for example in this user table there is "usertype" that specify if the user is normal user or admin i want to user the same code above but to display a specific usertype i tried this: <?php use Illuminate\Support\Facades\DB; $users = DB::table('users')->count()->WHERE usertype =admin; echo $users; ?> but it didn't work, what am i doing wrong? source https://stackoverflow.com/questions/68199726/how-to-show-number-of-registered-users-in-laravel-based-on-usertype

Why is my reports service not connecting?

I am trying to pull some data from a Postgres database using Node.js and node-postures but I can't figure out why my service isn't connecting. my routes/index.js file: const express = require('express'); const router = express.Router(); const ordersCountController = require('../controllers/ordersCountController'); const ordersController = require('../controllers/ordersController'); const weeklyReportsController = require('../controllers/weeklyReportsController'); router.get('/orders_count', ordersCountController); router.get('/orders', ordersController); router.get('/weekly_reports', weeklyReportsController); module.exports = router; My controllers/weeklyReportsController.js file: const weeklyReportsService = require('../services/weeklyReportsService'); const weeklyReportsController = async (req, res) => { try { const data = await weeklyReportsService; res.json({data}) console...

How to split a rinex file if I need 24 hours data

Trying to divide rinex file using the command gfzrnx but getting this error. While doing that getting this error msg 'gfzrnx' is not recognized as an internal or external command Trying to split rinex file using the command gfzrnx. also install'gfzrnx'. my doubt is I need to run this program in 'gfzrnx' or in 'cmdprompt'. I am expecting a rinex file with 24 hrs or 1 day data.I Have 48 hrs data in RINEX format. Please help me to solve this issue. source https://stackoverflow.com/questions/75385367/how-to-split-a-rinex-file-if-i-need-24-hours-data