JSFiddle - React, Tailwind, and code Playground

by Aaron Zhang

HTML

<!doctype html>
<html lang="en">

  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Bootstrap demo</title>
    <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-GLhlTQ8iRABdZLl6O3oVMWSktQOp6b7In1Zl3/Jr59b6EGGoI1aFkw7cmDA6j6gD" crossorigin="anonymous">
  </head>

  <body>
    <div class="container-sm">
      <div class="row align-items-center">
        <div class="col">
          <form>
            <div class="mb-3">
              <label for="carbWeight" class="form-label">碳水化合物/份(g)</label>
              <input type="number" class="form-control" id="carbWeight">
            </div>
            <div class="mb-3">
              <label for="servingSize" class="form-label">份量(g)</label>
              <input type="number" class="form-control" id="servingSize" value="100">
            </div>
            <div class="mb-3">
              <label for="targetWeight" class="form-label">目标碳水重量(g)</label>
              <input type="number" class="form-control" id="targetWeight" value="35">
            </div>
            <div class="mb-3">
              <label for="foodWeight" class="form-label">食物重量(g)</label>
              <input type="number" class="form-control" id="foodWeight" readonly>
            </div>
          </form>
        </div>
      </div>
    </div>
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-w76AqPfDkMBDXo30jS1Sgez6pr3x5MlQ1ZAGC+nuZB+EYdgRZgiwxhTBTkF7CXvN" crossorigin="anonymous"></script>
  </body>

</html>

JavaScript

const $carbWeight = $("#carbWeight");
const $servingSize = $("#servingSize");
const $targetWeight = $("#targetWeight");
const $foodWeight = $("#foodWeight");

function calculate() {
  const carbWeight = $carbWeight.val();
  const servingSize = $servingSize.val();
  const targetWeight = $targetWeight.val();

  if (!carbWeight || !servingSize || !targetWeight) {
    return;
  }
  $foodWeight.val((targetWeight / (carbWeight / servingSize)).toFixed(2));
}

$carbWeight.keyup(calculate);
$servingSize.keyup(calculate);
$targetWeight.keyup(calculate);