Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

339
Visualizações
Javascript function to calculate window areas in a table

I'm just working on a simple calculator for a small project of mine. I'm just hoping to get help with my calculatArea1 function.

I'll attach a few images showing the webpage, html code, and Javascript.

The html starts with a empty row with 3 cells so the user can add in the height and width of the window. Then, there's a button that allows the user to add a new row/window. This is all working fine.

The problem I'm having is, whenever I add multiple rows, then start adding in the width & height then click calculate it will only calculate the top row.

I though I might add also, if I start fresh with one row, then add the height & width, then click calculate. Then, click add window, then add the width & height, then calculate again. it works.

I just want to be able to add in as many rows as I need, then add in the data, then click calculate.

Any suggestions would be much appreciated, cheers!

HTML

        <table id="table1">
            <tr>
                <th>Height</th>
                <th>Width</th>
                <th>Area</th>
            </tr>
            <tr>
                <td><input class="height" type="text"></td>
                <td><input class="width" type="text"></td>
                <td><div class="area"></div></td>
            </tr>
        </table>

This is my Javascript functions

function addWindow1() {
   var table1 = document.getElementById("table1");
   var row1 = table1.insertRow(1);
   var cell1 = row1.insertCell(0);
   var cell2 = row1.insertCell(1);
   var cell3 = row1.insertCell(2);
   cell1.innerHTML = '<input class="height" type="text">';
   cell2.innerHTML = '<input class="width" type="text">';
   cell3.innerHTML = '<div class="area"></div>';
};


function calculateArea1() {
   var table1 = document.getElementById("table1");
   for(var i = 0; row = table1.rows[i]; i++){
       var height = document.querySelector('.height').value;
       var width = document.querySelector('.width').value;
       var area = document.querySelector('.area');
       var areaResult = height * width;
       area.innerHTML = areaResult;
    };
 };

enter image description here

This is what happens if I add multiple rows first, then add in the width & height, then click calculate

This is what happens if I add multiple rows first, then add in the width & height, then click calculate

over 4 years ago · Santiago Trujillo
2 Respostas
Responde à pergunta

0

In the for loop, you should select the width/height from the current row instead of from the DOM.

// select the first item with class `height` in the DOM => not what you want
var height = document.querySelector('.height').value;

// this should work
var height = row.querySelector('.height').value;
over 4 years ago · Santiago Trujillo Relatório

0

You are only getting one element with querySelector inside the calculateArea1 function. You should loop over every row and update the area with the values of width and height of that row.

One way to do this is to give a class (lets say data) to rows that contain the width, height and area cells then loop over all elements with that data class and access the cells inside it with a querySelector.

You can simplify your addWindow1 function to this:

function addWindow1() {
  const row1 = table1.insertRow(1)
  row1.className = 'data'
  row1.innerHTML = `
      <td><input class="height" type="text" /></td>
      <td><input class="width" type="text" /></td>
      <td><div class="area"></div></td>
      `
}

Then update your calculateArea1 function as follows:

function calculateArea1() {
  const data = document.querySelectorAll('.data')

  for (let i = 0; i < data.length; i++) {
    const height = data[i].querySelector('.height').value
    const width = data[i].querySelector('.width').value
    data[i].querySelector('.area').textContent = height * width
  }
}

Here is a working example:

const add = document.getElementById('add')
const calc = document.getElementById('calc')
const table1 = document.getElementById('table1')

add.addEventListener('click', addWindow1)
calc.addEventListener('click', calculateArea1)

function addWindow1() {
  const row1 = table1.insertRow(1)
  row1.className = 'data'
  row1.innerHTML = `
      <td><input class="height" type="text" /></td>
      <td><input class="width" type="text" /></td>
      <td><div class="area"></div></td>
      `
}

function calculateArea1() {
  const data = document.querySelectorAll('.data')

  for (let i = 0; i < data.length; i++) {
    const height = data[i].querySelector('.height').value
    const width = data[i].querySelector('.width').value
    data[i].querySelector('.area').textContent = height * width
  }
}
<button id="add">add</button>
<button id="calc">calc</button>
<table id="table1">
  <tr>
    <th>Height</th>
    <th>Width</th>
    <th>Area</th>
  </tr>
  <tr class="data">
    <td><input class="height" type="text" /></td>
    <td><input class="width" type="text" /></td>
    <td>
      <div class="area"></div>
    </td>
  </tr>
</table>

over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda