通过动态创建的表单行和输入的迭代减去

时间:2018-10-24 18:16:41

标签: javascript jquery html

我有一个用于记录餐食及其营养信息的应用程序。在页面顶部,我希望统计用户的每日目标以及他们剩余的卡路里,蛋白质,脂肪和碳水化合物。我目前有一个输入表单,可以动态添加行并每餐输入更多食物,该表单会附加到页面底部的食物日志中。

问题:我无法弄清楚如何从“每日目标”中减去所有可能的动态输入并将其显示在“剩余”列旁边。我能得到的最接近的是它从每日中减去最后一行的值并显示出来。

请在下面查看我的代码:

$(document).ready(function() {

  var dailyCal = 2000;
  var dailyPro = 125;
  var dailyFat = 56;
  var dailyCar = 250;

  $("#calGoal").text("Calories: " + dailyCal);
  $("#proGoal").text("Protein: " + dailyPro + "g");
  $("#fatGoal").text("Fat: " + dailyFat + "g");
  $("#carGoal").text("Carbs: " + dailyCar + "g");

  // On Submit
  var count = 1;
  $("#submit").on("click", function(event) {

    event.preventDefault();

    var $header = $("<h5 class='text-left' style='font-weight: bold;'>Meal " + count++ + "</h5>");
    $("#meals").append($header);

    $(".food").each(function() {

      // Assigns all values from all inputs on all dynamic rows to variables
      var food = $(this).find(".col1").val().trim();
      var calories = $(this).find(".col2").val().trim();
      var protein = $(this).find(".col3").val().trim();
      var fat = $(this).find(".col4").val().trim();
      var carbs = $(this).find(".col5").val().trim();

      var calRem = 2000;
      var proRem = 125;
      var fatRem = 56;
      var carRem = 250;

      $("#calRem").text("Calories: " + (calRem - calories));
      $("#proRem").text("Protein: " + (proRem - protein) + "g");
      $("#fatRem").text("Fat: " + (fatRem - fat) + "g");
      $("#carRem").text("Carbs: " + (carRem - carbs) + "g");

      // Appends all variables to the ID 'meals'
      $("#meals").append("<tr class='row text-center'><td class='col-sm-3'>" + food + "</td><td class='col-sm-2'>" + calories + "</td><td class='col-sm-2'>" + protein + "</td><td class='col-sm-2'>" + fat + "</td><td class='col-sm-2'>" + carbs + "</td><br>");

    });

    $("#foodName").val("");
    $("#calories").val("");
    $("#protein").val("");
    $("#fat").val("");
    $("#carbs").val("");

    $(".dynamic").val("");
    $(".dynamicRow").remove();

  });

  // Add Row Button
  var counter = 1;
  $("#addRow").on("click", function() {
    var newRow = $("<tr>");
    newRow.addClass("row dynamicRow food");

    var cols = "";
    cols += '<td class="col-sm-3"><input type="text" class="form-control col1 dynamic" id="foodName' + counter + '"/></td>';
    cols += '<td class="col-sm-2"><input type="text" class="form-control col2 dynamic" id="calories' + counter + '"/></td>';
    cols += '<td class="col-sm-2"><input type="text" class="form-control col3 dynamic" id="protein' + counter + '"/></td>';
    cols += '<td class="col-sm-2"><input type="text" class="form-control col4 dynamic" id="fat' + counter + '"/></td>';
    cols += '<td class="col-sm-2"><input type="text" class="form-control col5 dynamic" id="carbs' + counter + '"/></td>';
    cols += '<td class="col-sm-1 dynamic"><span id="clickFA"><i class="ibtnDel fas fa-trash-alt fa-2x trash"></span></td>';

    newRow.append(cols);
    $("#inputTable").append(newRow);
    counter++;
  });

  $("table.order-list").on("click", ".ibtnDel", function(event) {
    $(this).closest("tr").remove();
    counter -= 1;
  });

});
@import url('https://fonts.googleapis.com/css?family=Roboto');
body {
  font-family: 'Roboto', sans-serif;
  overflow-x: hidden;
  background: url('../styles/img/gravel.png');
}


/* Navbar */

#navbar {
  box-shadow: 0px 0px 4px 1px;
}

#brand {
  background: rgb(10, 177, 93);
  padding: 3px;
  border-radius: 3px;
  font-size: 30px;
}

#navBtn {
  background: black;
}

.nav-link {
  padding: 5px 0px 0px 0px;
}

#goalCard {
  margin: 40px 0px 40px 0px;
  box-shadow: 0px 0px 2px 1px;
  border: none;
}

#dailyGoal {
  font-weight: bold;
}

li {
  float: left;
  list-style: none;
}

#userForm {
  margin-bottom: 40px;
  width: 100%;
  box-shadow: 0px 0px 2px 1px;
  border: none;
}

.trash {
  cursor: pointer;
}

#mealLog {
  margin-bottom: 40px;
  box-shadow: 0px 0px 2px 1px;
  border: none;
}

#logHeader {
  font-weight: bold;
}

#title {
  z-index: 100;
  position: relative;
}

#submit {
  float: left;
}

#addRow {
  float: right;
}

#motto {
  font-size: 20px;
  font-style: italic;
}

#form {
  box-shadow: 0px 0px 4px 2px gray;
  border: none;
  margin-bottom: 10px;
}

#addMeal {
  font-weight: bold;
  font-size: 35px !important;
}


/* Footer */

.footer {
  /* position: relative; */
  width: 100%;
  height: 80px;
  bottom: 0;
  padding: 20px;
}

#footerSpan {
  font-weight: bold;
  font-size: 18px;
}

@media (min-width: 992px) {
  body {
    padding-top: 56px;
  }
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!DOCTYPE html>
<html lang="en-us">

<head>

  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>BiteTracker</title>
  <!-- Bootstrap CDN -->
  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">
  <!-- CSS -->
  <link rel="stylesheet" href="styles/styles.css">
  <!-- Font Awesome -->
  <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.4.1/css/all.css" integrity="sha384-5sAR7xN1Nv6T6+dT2mhtzEpVJvfS3NScPQTrOxhwjIuvcA67KV2R5Jz6kr4abQsz" crossorigin="anonymous">
  <!-- Firebase JavaScript Link -->
  <script src="https://www.gstatic.com/firebasejs/4.12.0/firebase.js"></script>

</head>

<body>

  <!-- Navbar -->
  <nav class="navbar navbar-expand-lg navbar-dark bg-dark fixed-top" id="navbar">
    <div class="container">
      <a class="navbar-brand" href="index.html" id="brand"><i class="fas fa-cookie-bite"></i> BiteTracker</a>
      <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarResponsive" aria-controls="navbarResponsive" aria-expanded="false" aria-label="Toggle navigation">
                <span class="navbar-toggler-icon"></span>
            </button>
      <div class="collapse navbar-collapse" id="navbarResponsive">
        <ul class="navbar-nav ml-auto">
          <li class="nav-item active">
            <a class="nav-link" href="#">Home
                            <span class="sr-only">(current)</span>
                        </a>
          </li>
          <li class="nav-item">
            <a class="nav-link" href="./profile.html">Profile</a>
          </li>
          <li class="nav-item">
            <a class="nav-link" href="./signin.html">Sign-Out</a>
          </li>
        </ul>
      </div>
    </div>
  </nav>

  <!-- Site Body -->
  <div class="container">

    <!-- Remaining Card -->
    <div class="row">
      <div class="card col-sm-12" id="goalCard">
        <div class="card-body">
          <ul id="dailyGoal">
            <li class="col-sm-3">Your Daily Goals:</li>
            <li class="col-sm-2" id="calGoal"></li>
            <li class="col-sm-2" id="proGoal"></li>
            <li class="col-sm-2" id="fatGoal"></li>
            <li class="col-sm-2" id="carGoal"></li>
          </ul>
          <ul id="remaining">
            <li class="col-sm-3">Remaining:</li>
            <li class="col-sm-2" id="calRem">Calories: 2000</li>
            <li class="col-sm-2" id="proRem">Protein: 125g</li>
            <li class="col-sm-2" id="fatRem">Fat: 56g</li>
            <li class="col-sm-2" id="carRem">Carbs: 250g</li>
          </ul>
        </div>
      </div>
    </div>

    <!-- User Meal Submit -->
    <div class="row text-center">
      <div class="card bg-light text-dark" id="userForm">
        <div class="card-body">
          <h2 class="text-center" id="addMeal">Add Meal</h2>
          <table id="inputTable" class="table order-list">
            <thead>
              <tr class="row text-center">
                <td class="col-sm-3">Food</td>
                <td class="col-sm-2">Calories</td>
                <td class="col-sm-2">Protein (g)</td>
                <td class="col-sm-2">Fat (g)</td>
                <td class="col-sm-2">Carbs (g)</td>
                <td class="col-sm-1"></td>
              </tr>
            </thead>
            <tbody>
              <tr class="row food" id="staticRow">
                <td class="col-sm-3">
                  <input type="text" id="foodName" name="foodName" class="col1 form-control" />
                </td>
                <td class="col-sm-2">
                  <input type="text" id="calories" name="calories" class="col2 form-control" />
                </td>
                <td class="col-sm-2">
                  <input type="text" id="protein" name="protein" class="col3 form-control" />
                </td>
                <td class="col-sm-2">
                  <input type="text" id="fat" name="fat" class="col4 form-control" />
                </td>
                <td class="col-sm-2">
                  <input type="text" id="carbs" name="carbs" class="col5 form-control" />
                </td>
                <td class="col-sm-1"></td>
              </tr>
            </tbody>
          </table>
          <button type="submit" class="btn btn-primary" id="submit">Submit</button>
          <button type="button" class="btn btn-success" id="addRow" value="Add Row">Add
                        Row</button>
        </div>
      </div>
    </div>

    <!-- Meal Log -->
    <div class="row text-center">
      <div class="card col-sm-12 bg-light text-dark" id="mealLog">
        <div class="card-body">
          <h2 class="text-center" id="logHeader">Meal Log</h2>
          <table id="logTable" class="table order-list text-center">
            <thead>
              <tr class="row text-center">
                <td class="col-sm-3" id="foodEntry">Food</td>
                <td class="col-sm-2" id="caloriesEntry">Calories</td>
                <td class="col-sm-2" id="proteinEntry">Protein (g)</td>
                <td class="col-sm-2" id="fatEntry">Fat (g)</td>
                <td class="col-sm-2" id="carbsEntry">Carbs (g)</td>
              </tr>
            </thead>
            <tbody id="meals">
              <td></td>
            </tbody>
          </table>
        </div>
      </div>
    </div>
  </div>

  <!-- Footer -->
  <footer class="footer bg-dark text-light">
    <div class="col-sm-12 text-center">
      <span id="footerSpan">BiteTracker &copy; 2018</span>
    </div>
  </footer>

  <!-- JQuery -->
  <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
  <!-- jQuery -->
  <script src="https://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js" integrity="sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49" crossorigin="anonymous"></script>
  <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js" integrity="sha384-ChfqqxuZUCnJSK3+MXmPNIyE6ZbWh2IMqE241rYiqJxyMiZ6OW/JmZQ5stwEULTy" crossorigin="anonymous"></script>
  <!-- JavaScript -->
  <script src="../public/js/firebase.js"></script>
</body>

</html>

感谢您抽出宝贵的时间来帮助您!

1 个答案:

答案 0 :(得分:0)

不是在calRem循环内定义.each变量。在每日目标变量旁边的顶部定义它们。这样一来,它们就不会为循环中的每个项目重置。

然后,当您循环浏览时,只需使用calRem = calRem - current_item_value来跟踪剩余金额。

编辑:

由于使用Java语言进行了闭包,因此,作为父级子级的所有函数都可以访问函数中定义的变量。这样做的好处是,您只需定义一次变量,给它们一个值,然后代码就可以在该父函数中访问这些值,从而允许您在循环中调用它。

当您调用它时,会发生两件事:

1)变量仍处于“范围内”,因此可以访问(否则您将看到“未定义”) 2)可以从多个子功能访问/更改值