What am I missing? Calculation won't show in the field

Issue

I am trying to make an area calculator and I cannot figure out what am I missing.

the area field is not updating when entering numbers in each field.

Any advice please? I wonder if I’m missing something very important.

function calculateArea() {
  var form = document.getElementById("calc");
  var sLength = parseFloat(form.elements["slab_length"].value);
  var sHeight = parseFloat(form.elements["slab_width"].value);

  var slabsArea = sHeight * sLength;

  //slabsArea = Math.round(slabsArea);
  //document.getElementById("slabsArea").value = slabsArea;
  form.elements["slabsArea"].value = slabsArea;
  return slabsArea;
}
<form id="calc">
  <table>
    <tr>
      <th style="text-align: left;"><label>Slab Width (m): </label></th>
      <th>
        <div class="input-box">
          <input type="text" name="slab_width" onkeypress="return isNumber(event)" onkeyup="calculateArea()" required="" class="form-control">
        </div>
      </th>
    </tr>
    <tr>
      <th style="text-align: left;"><label>Slab Length (m): </label></th>
      <th>
        <div class="input-box">
          <input type="text" name="slab_length" onkeypress="return isNumber(event)" onkeyup="calculateArea()" required="" class="form-control">
        </div>
      </th>
    </tr>
    <tr>
      <th style="text-align: left;"><label>Total Area (m2):</label></th>
      <th>
        <div class="input-box">
          <input type="text" name="slabsArea" disabled="" class="form-control">
        </div>
      </th>
    </tr>

  </table>
</form>

Solution

I’ll simplify this for you, and you can update your HTML table as needed to format it in a way you’d like.

First, don’t use keypress, use keyup. This will get the updated value of the input.

Next, use numeric inputs to enforce numbers. It’s built in, and much easier than writing your own numeric parser. Here’s sample HTML:

Third, add IDs to your elements. It makes selecting them much more efficient and easy.

Here’s a sample using inputs and event listeners for brevity:

window.addEventListener("DOMContentLoaded", () => {
  const userInputs = document.getElementsByClassName("userInput");
  for (let x=0, input; input = userInputs[x]; x++)
  {
    input.addEventListener("keyup", (evt) => { 
      let length = parseFloat(document.getElementById("slabLength").value);
      let width = parseFloat(document.getElementById("slabWidth").value);
      document.getElementById("slabArea").value = length * width;
    })
  }
});
<input id="slabLength" class="userInput" type="number" value="0">
<input id="slabWidth" class="userInput" type="number" value="0">
<input id="slabArea" type="number" readonly value="0">

Answered By – Matthew M.

Answer Checked By – Marie Seifert (AngularFixing Admin)

Leave a Reply

Your email address will not be published.