JavaScript Array for automatic calculation of input texts

How can I create an array that allows for auto calculation across multiple input fields? The current issue is that while the auto calculation functions properly for the first row, it fails to work on the second and third rows. My goal is to have this functionality extended over 15 rows.

Any assistance or guidance on this matter would be greatly appreciated.

<html>
<head>
<script type="text/javascript>
function calc(){
var textValues = [];
for(var i = 1; i <= 10; i++) {
    textValues.push(document.getElementById('input' + i).value);
}
var total = 0;
for(var j = 0; j < textValues.length; j++){
    total += textValues[j] * (10 - j);
}
document.getElementById('output').value = total;
 }
</script>
</head>

<body>
[...]

Answer №1

The problem is quite straightforward - each HTML element can only have one unique id. You've assigned the same ID to multiple elements.

When using the Javascript getElementById method, it will only select the first element with that specific id and disregard any others.

As a result, the first row functions perfectly while the subsequent rows are overlooked.

To resolve this issue, ensure that each element has a distinct ID. Alternatively, consider utilizing the getElementsByClassName method and assign a unique class to each row.

Answer №2

If you want to perform dynamic calculations, you can utilize the DOM's querySelectorAll method.

function calculateSum(rowNumber){
var cells = document.querySelectorAll("#table tr:nth-child("+(rowNumber+2)+") td");

var sum = 0;
for (var i = 0; i < cells.length; i++) {
   var value = parseFloat(cells[i].firstChild.value) * (10 - i);
   if (!isNaN(value)) {
      sum+=value;
   }
}
cells[10].firstChild.value = sum;
 }
<table id="table">
  <tr>
  <td>10</td>
  <td>9</td>
  <td>8</td>
  <td>7</td>
  <td>6</td>
  <td>5</td>
  <td>4</td>
  <td>3</td>
  <td>2</td>
  <td>1</td>
  <td>Total</td>
  </tr>
  
  <tr>
  <td><input size="8" onkeyup="calculateSum(0)" value=""></td>
  <td><input size="8" onkeyup="calculateSum(0)" value=""></td>
  <td><input size="8" onkeyup="calculateSum(0)" value=""></td>
  <td><input size="8" onkeyup="calculateSum(0)" value=""></td>
  <td><input size="8" onkeyup="calculateSum(0)" value=""></td>
  <td><input size="8" onkeyup="calculateSum(0)" value=""></td>
  <td><input size="8" onkeyup="calculateSum(0)" value=""></td>
  <td><input size="8" onkeyup="calculateSum(0)" value=""></td>
  <td><input size="8" onkeyup="calculateSum(0)" value=""></td>
  <td><input size="8" onkeyup="calculateSum(0)" value=""></td>
  <td><input size="8" value="" id="total"></td>
  </tr>
  <tr>
  <td><input size="8" onkeyup="calculateSum(1)" value=""></td>
  <td><input size="8" onkeyup="calculateSum(1)" value=""></td>
  <td><input size="8" onkeyup="calculateSum(1)" value=""></td>
  <td><input size="8" onkeyup="calculateSum(1)" value=""></td>
  <td><input size="8" onkeyup="calculateSum(1)" value=""></td>
  <td><input size="8" onkeyup="calculateSum(1)" value=""></td>
  <td><input size="8" onkeyup="calculateSum(1)" value=""></td>
  <td><input size="8" onkeyup="calculateSum(1)" value=""></td>
  <td><input size="8" onkeyup="calculateSum(1)" value=""></td>
  <td><input size="8" onkeyup="calculateSum(1)" value=""></td>
  <td><input size="8" value="" id="total"></td>
  </tr>
</table>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is it possible to automatically update views immediately after performing a CRUD operation?

In my basic CRUD application, I am facing an issue when making an AJAX call to delete a document. I want the view to be updated with the new list of documents immediately after deletion. I have experimented with using ajaxStop / ajaxSuccess and setTimeout ...

Error message encountered: ReferenceError - The subcommand specified in Discord.js Slash Command function is undefined

I have been experimenting with subcommands in a slash command for a discord bot. I plan to have several similar subcommands, so I wanted to create a function that can be called within .addSubCommand, but it seems like it's not functioning correctly. ...

Ways to execute various JavaScript functions based on the outcome of an AJAX request?

Currently, I am working on implementing some AJAX functionality where the actions in my JavaScript code depend on the response from the PHP file. Let me illustrate with an example: $.ajax({ type: 'POST', url: '/something.php', ...

How can I utilize data from the server on the client using React and NodeJS?

I am looking to implement data received from a server on the client side. My setup involves a NodeJS Server with NextJS and React. Here is the function used on the server: function addEmailToMailChimp(email, callback) { var options = { method ...

Tips for adding an asterisk to the label of a Material-UI switch component

I am trying to include an asterisk symbol in the label by passing a required prop with a property, but it doesn't seem to be functioning correctly. <FormControlLabel control={ <Switch onChange={event => ...

Organize Array based on an object

I have an array storing objects and I need to sort the names based on their 'is_main' property. The object with 'is_main' set to 1 should appear first, followed by those with 'is_main' set to 0. Below is the Object array(2){ ...

The Map/Reduce function is producing incorrect results because of null values, causing me to receive NaN or erroneous

I am ready to delve into another Map/Reduce query. Within my database, I have a collection named "example" which is structured like this: { "userid" : "somehash", "channel" : "Channel 1" } The Map/Reduce functions I am using are as follows: var map = f ...

Is it possible for PHP to dynamically load a file based on a condition set in JavaScript?

I am attempting to dynamically insert a PHP include onto the page once the user scrolls to a specific part of the page. Is this feasible? For example: var hasReachedPoint = false; $(window).scroll(function() { var $this = $(this); if ($this.scrollTo ...

What could be the reason for the Ajax call not being triggered?

My attempt to add a filter to the map data display is facing an issue where the Ajax call I have set up does not get executed. Although I can see the console.log line in the view, the code after that in the Ajax call fails to run properly. This problem ari ...

Choose a particular button using JavaScript and AJAX

In my Django app, users can save different items to a list. Each item has a corresponding delete button next to it. Currently, when I click on any delete button, it always selects and deletes the first item in the list. This is because my JavaScript code ...

Guide on redirecting to another webpage after submitting a Django form and securely saving form data to the backend database

Objective: Ensure that data submitted through a Django form is successfully saved on the admin side. Issue: Although able to redirect to another page after submitting the form, the data does not get saved on the admin side. How can I resolve this using ei ...

Updating the class of the "like" button icon using an AJAX form within the HTML view of a Ruby on Rails application

I'm facing an issue where my page isn't updating the icon after a successful Ajax function. Even though the data is posted to the database without any problems, the content doesn't refresh unless I manually reload the page. I want to be able ...

AngularJS seems to be ignoring CSS styles when displaying list items in the ng-repeat loop

After coming across a tutorial on creating round circles connected by a line in CSS, I decided to implement it myself. Interestingly, everything worked perfectly fine when I tested it with static HTML. However, when I tried to make it dynamic using Angular ...

Formula in Excel for generating a list of values that do not match between two specified ranges according to specific criteria

Any assistance is greatly appreciated in achieving a comprehensive list of all non-matching values between two distinct ranges (which are located on different sheets, but since named ranges are being utilized, it shouldn't pose an issue). The first r ...

Associating specific information with individual elements utilizing HTML text box

Seeking guidance on implementing annotations feature for a scatter-plot using d3.js v3. My goal is to show a text-box upon clicking each data point, then display that entered text as a tool-tip specific to that data point. Here's how I'm approach ...

Data not showing up in res.render

I've developed a function that organizes email addresses in various formats and validates them. While everything is functioning correctly on the server-side, I'm encountering difficulties trying to showcase the results within my Jade template. De ...

Creating an object in JavaScript using variables

Is it possible to create an object with keys coming from a variable parameter? Let's say 'prod_id' holds a value, and I want to create an object with key 'prod_id' and value 1. Can this be achieved? If so, how? Thank you! var cart ...

Utilizing Randomized Values for Nonces in JavaScript Inline Scripts: A Guide

I've been struggling to generate random values for the nonce attribute, but for some reason, they aren't showing up when I check the generated value. Here's the code I'm using: It keeps returning an error saying getRandomValues is not ...

When using the `Node fs.readstream()` function, the output includes `<Buffer 3c 3f 78 6d 6c ...>`, which is not in a readable

Handling a large XML file (~1.5gb) in Node Js by streaming it to process data in chunks has proven challenging due to the complexity of the documentation. A simple code snippet I am currently using is: var fs = require('fs'); var stream = fs.c ...

Sorting and searching through multiple values using data structures in Rails

Currently, I am developing a software tool that takes input data from your golf game to determine your handicap. In addition to this feature, I have also included a table on the side of the program similar to Excel. This table consists of golf course names ...