Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

343
Views
Función Javascript para calcular áreas de ventana en una tabla

Solo estoy trabajando en una calculadora simple para un pequeño proyecto mío. Solo espero obtener ayuda con mi función calculatArea1.

Adjuntaré algunas imágenes que muestran la página web, el código html y Javascript.

El html comienza con una fila vacía con 3 celdas para que el usuario pueda agregar el alto y el ancho de la ventana. Luego, hay un botón que le permite al usuario agregar una nueva fila/ventana. Esta todo trabajando bien.

El problema que tengo es que, cada vez que agrego varias filas, luego comienzo a agregar el ancho y la altura, luego hago clic en calcular, solo calculará la fila superior.

Pensé que también podría agregar, si empiezo de nuevo con una fila, luego agrego la altura y el ancho, luego hago clic en calcular. Luego, haga clic en agregar ventana, luego agregue el ancho y la altura, luego calcule nuevamente. funciona.

Solo quiero poder agregar tantas filas como necesite, luego agregar los datos y luego hacer clic en calcular.

Cualquier sugerencia sería muy apreciada, saludos!

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>

Estas son mis funciones Javascript

 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; }; };

ingrese la descripción de la imagen aquí

Esto es lo que sucede si agrego varias filas primero, luego agrego el ancho y la altura, luego hago clic en calcular

Esto es lo que sucede si agrego varias filas primero, luego agrego el ancho y la altura, luego hago clic en calcular

over 4 years ago · Santiago Trujillo
2 answers
Answer question

0

En el ciclo for, debe seleccionar el ancho/alto de la fila actual en lugar del 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 Report

0

Solo obtiene un elemento con querySelector dentro de la función calculateArea1 . Debe recorrer cada fila y actualizar el área con los valores de ancho y alto de esa fila.

Una forma de hacer esto es dar una clase (digamos data ) a las filas que contienen las celdas de ancho, alto y área, luego recorrer todos los elementos con esa clase data y acceder a las celdas dentro de ella con un querySelector .

Puede simplificar su función addWindow1 a esto:

 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> ` }

Luego actualice su función de calculateArea1 de la siguiente manera:

 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 } }

Aquí hay un ejemplo de trabajo:

 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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!