Determining the total of input values based on identification number

Can anyone help me figure out how to calculate the total sum of the values entered using IDs?

I've been struggling with it and can't seem to get it to work.

Your assistance would be greatly appreciated.

<input type="number" id="do" name="i1">

  <input type="number" id="to" name="i2">

$("#do").keyup(function() {
  var totalSum = 0;
  $("#to").each(function() {
    totalSum += Number($(this).val());
  });
  $('#total-amount').text(totalSum + ' usd');
});

Answer №1

Your example is almost prepared. The issue lies in not utilizing the value of $("#do"):

$("#do").keyup(function() {
  var total = Number($(this).val());
  $("#to").each(function() {
    total += Number($(this).val());
  });
  $('#tot-qty').text(total + ' usd');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="number" id="do" name="i1">

  <input type="number" id="to" name="i2">

<span id="tot-qty"></span>

EDIT:

Based on the suggestion in the previous answer, it can be made more general:

$(".summe").keyup(function() {
  var total = 0;
  $(".summe").each(function() {
    total += Number($(this).val());
  });
  $('#tot-qty').text(total + ' usd');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="number" id="do" class="summe" name="i1">

  <input type="number" id="to" class="summe" name="i2">

<span id="tot-qty"></span>

Answer №2

It's essential for HTML "id" attributes to be unique within the DOM to avoid undesired behavior. Having multiple elements with the same "id" may not trigger an error, but it will not function as intended.

If you encounter this issue, consider changing the "id" to a "class" instead. Another solution could be using jQuery's selectors, depending on your overall markup structure.

For example, you can use the following code snippet:

var allInputElements = $(":input");
allInputElements.each(function(){ ... })

Answer №3

If you want to perform a sum operation on multiple elements, it's best to use classes instead of ids. Convert the values to integers and create a new class that can be added to each element you wish to include in the sum. Remember, the each function won't work with ids since each id represents a unique element.

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

AngularJS bidirectional binding with numerous select choices

I am faced with a unique challenge - I have a list of non-exclusive fields that users want to see presented in a select box allowing multiple selections, rather than individual checkboxes bound to Boolean values in the model. While I know how to create t ...

Keep only one accordion panel open at a time

$(document).ready(function(){ var allPanels = $('.accordian li div'); allPanels.hide(); $('#nav-list li a').click(function() { var id; if(this.id == id) { allPanels.slideUp('slow'); alert("hello"); } else { allPanels.slideU ...

Regular expression for identifying a specific attribute paired with its corresponding value in a JSON object

Below is a JSON structure that I am working with: 'use strict'; // some comment is going to be here module.exports = { property1: 'value1', property2: 999, }; I am looking to remove the property2: 999, from the JSON. I attempted ...

What steps should I take to modify the jQuery find selector when I convert the name of the input form field into an array?

Currently updating some code to dynamically include form fields. Initially, it looked like this: <input name="projDesc" /> Then I used the following function to generate additional fields: function GetHtml() { var len = $('.extraProject& ...

What is preventing me from integrating angular-cookies into my application?

I'm struggling to resolve this issue where I can't seem to make it work. My aim is to integrate NgCookies (angular-cookies) into my application, but all I'm encountering are errors. This is what I currently have: JS files being included: ...

Is there a way to adjust the sizes of images within a flexbox layout?

I am currently working on developing a website for my portfolio and I want to achieve a similar layout to this: https://i.stack.imgur.com/giJNF.png However, I am facing some difficulties with displaying the Twitter/Instagram and Deviantart icons. I am usi ...

Step-by-step guide on redirecting a page using AJAX while also sending data to a controller

Is it possible to redirect to another page after a successful action, but not able to retrieve the data that was passed? Here is the jQuery code: $.ajax({ type:'GET', url:link, data:data, success:functio ...

Arranging serialized information from a tabular format and retrieving specific data

: I'm currently attempting to utilize an AJAX POST request to send data from a dynamic webpage that includes information gathered from a table form, a date selection box, and comment text input. The webpage is generated as a PHP file on a GET request ...

keep the color of the link after clicking until a different link is clicked

At the bottom of every post on my website, there are 3 buttons: "Written By", "Related Post," and "In This Category": SoCatchy! I'm looking to have each button change color when clicked, and stay that way until another link is clicked. Here is the c ...

Error: The object referenced does not have a function called 'findById' within its methods when trying to export

I have come across a number of similar questions on this platform, but most of them seem to be related to HTML. My issue involves encountering an error while submitting a login form in Java. Here is a Very Simple Save Function: var model = require(' ...

Trigger an Angular controller within Foundation's reveal modal

Trying to implement a form using foundation's reveal modal, I want to incorporate an angular controller within the form for ajax form submission instead of the default post/refresh behavior. This is my primary view: <html lang="es" ng-app="crm"&g ...

Looping through PHP code to encapsulate HTML elements

As a newcomer to PHP, I appreciate your patience as I navigate this new language. My goal is to wrap a div around elements like the "h4" tag without disrupting the for loop. Is this achievable? Thank you. <?php $con=mysqli_connect("localhost","root"," ...

How can I make Backbone.js execute a function following the creation of a Collection?

It seems like I may not be grasping the full picture here, but let me lay out my current understanding: I have a Model that holds 'all' the data (JSON retrieved from a single URL). This model contains one or more Collections which are populated ...

Speedy Guide to Referencing Variables in JavaScript

I'm hoping for some clarification on this topic. Let's imagine I have 2 global variables: var myarray=[1,3,5,7,9],hold; and then I execute the following code: function setup() { alert (myarray[0]);//displays 1 hold=myarray; alert (hold);//seem ...

Encountered an error while attempting to execute the command npx create react app: spawn UNKNOWN error occurred

After attempting to execute a basic npx create-react-app, an unexpected error occurred: D:\>npx create-react-app abc npx: installed 67 in 4.255s Creating a new React app in D:\abc. Installing packages. This might take a couple of minutes. In ...

data is currently being uploaded to the storage, however, the grid is not displaying any

After loading JSON data into the store, I am unable to see any data in the grid. Can someone please point out what I might be doing wrong? Here's the code snippet for the grid: { xtype: 'gridpanel', ...

Issue with scroll animation across multiple div elements

I am working on a project where I have two main divs, one with the id of "left-div" and the other with the id of "right-div". In the "left-div", there are multiple nested divs each with their own unique id. The overflow-y property of the "left-div" is set ...

How to move content without affecting the background of the `<body>` using scrolling

Can I achieve a glass morphism effect on my page without moving the background of the body? I only want to move the .container. Is this feasible? I attempted using background-attachment: fixed, but it did not work for me. Here is the code snippet I have be ...

Passing data to a different JS file

Is there a way to pass the values of two variables to another JS file? var publicPath = path.resolve(__dirname, '/src/login'); app.use(express.static(publicPath)); app.get('/auth', function (request, response) { response.sendFile(p ...

Retrieving a value using forEach in protractor - Dealing with closures

I am facing an issue with the helper code below, as it is not returning the correct number of occurrences of a string. this.getActualFilteredStatusCount = function(strFilter){ return this.getTotalRows().then(function(count){ var totalCount = ...