Sum Numbers in HTML Inputs, JavaScript

Calculate sum from number type input fields by javascript

When changing the element value using the arrow symbols change event is fired.

Instead of keyup try with input event.

The input event fires when the value of an <input>, <select>, or <textarea> element has been changed.

Change:

$(this).keyup(function(){

To:

$(this).on('input',function(){

$(document).ready(function(){
//iterate through each textboxes and add keyup //handler to trigger sum event $(".txt").each(function() {
$(this).on('input',function(){ calculateSum(); }); });
});
function calculateSum() {
var sum = 0; //iterate through each textboxes and add the values $(".txt").each(function() {
//add only if the value is number if(!isNaN(this.value) && this.value.length!=0) { sum += parseFloat(this.value); }
}); //.toFixed() method will roundoff the final sum to 2 decimal places $("#sum").html(sum.toFixed(2));
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>Qty1 : <input class="txt" type="number" name="qty" id="qty1"/><br>Qty2 : <input class="txt" type="number" name="qty" id="qty2"/><br>Qty3 : <input class="txt" type="number" name="qty" id="qty3"/><br>Qty4 : <input class="txt" type="number" name="qty" id="qty4"/><br>Qty5 : <input class="txt" type="number" name="qty" id="qty5"/><br>Qty6 : <input class="txt" type="number" name="qty" id="qty6"/><br>Qty7 : <input class="txt" type="number" name="qty" id="qty7"/><br>Qty8 : <input class="txt" type="number" name="qty" id="qty8"/><br><br><br>Total : <span id="sum">0</span><br>

Auto Sum Input Values and Display Using Javascript

This is what I've come up with.

  • You are using same Id for multiple elements. I added the same class to the elements instead
  • You are using <input type='text' then checking for numbers using regex. A better approach would be to just use <input type='number'
  • Since maxlength does not work on type='number', I have used max to handle 6 digit limit.

function findTotal() {
const fees = document.querySelectorAll(".fee");
const total = document.querySelector("#total_fee");
let sum = 0;

fees.forEach(fee => {
if(fee.valueAsNumber){
sum += fee.valueAsNumber;
}
});
total.value = sum;
}
<tr>
<td width="20%">Admission Fee:</td>
<td width="80%"><input onchange="findTotal()" type="number" class="input_box fee" name="admission_fee" value="" min='0' max='999999'></td>
</tr>
<tr>
<td width="20%">Annual Fee:</td>
<td width="80%"><input onchange="findTotal()" type="number" class="input_box fee" name="annual_fee" value="" min='0' max='999999'></td>
</tr>
<tr>
<td width="20%">Paper Money Fee:</td>
<td width="80%"><input onchange="findTotal()" type="number" class="input_box fee" name="paper_money_fee" value="" min='0' max='999999'></td>
</tr>
<tr>
<td width="20%">Monthly Fee:</td>
<td width="80%"><input onchange="findTotal()" type="number" class="input_box fee" name="monthly_fee" value="" min='0' max='999999'></td>
</tr>
<tr>
<td width="20%">Remaining Balance:</td>
<td width="80%"><input onchange="findTotal()" type="number" class="input_box fee" name="remaining_balance" value="" min='0' max='999999'></td>
</tr>
<tr>
<td class="school_trow2" width="20%">Total Fee:</td>
<td class="school_trow2" style="padding: 3px 0;" width="80%"><input type="text" class="input_box" style="background: #8CDFFF; border: 1px solid #006991; color: #000;" name="total_fee" id="total_fee" size="5" value="" disabled></td>
</tr>

How to plus input numbers in HTML with JS

  1. getElementByID is a typo. The method is getElementById (small "d")

  2. Even if you corrected the typo var result = document.getElementById('num1 + num2+ num3+ num4'); won't do anything because 'num1 + num2+ num3+ num4' is not the id of any element. You want to assign the total of adding the values of those inputs together to the value attribute of your result element.

  3. You're not checking for any changes on those inputs for you to be able to create the total. For that you'll need a listener.

Here's a slightly more modern approach. It uses event delegation to attach a listener to a containing element to catch change events from the inputs as they "bubble up" the DOM. That listener calls the handleChange function.

The handleChange function resets the total, iterates over all the inputs, and adds their value to the total. Then the value of the result is set.

// Cache the elements
const container = document.querySelector('#container');
const inputs = document.querySelectorAll('input[type="number"]');
const result = document.querySelector('#result');

// Add a listener to the container
container.addEventListener('change', handleChange, false);

// Reset the total, iterate over the input elements,
// and add their value to the total, coercing the string
// to a number first. Finally add that total to the
// value of the `result` element
function handleChange() {
let total = 0;
inputs.forEach(input => total += Number(input.value));
result.value = total;
}
<div id="container">
<input type="number" name="pree">
<input type="number" name="pree1">
<input type="number" name="pree2">
<input type="number" name="pree3">
<br />
Result: <input id="result">
</div>

Sum of Fields from User input in javascript

You could give all of the sum fields a class name, then use document.getElementsByClassName to get all of them:

function ass() {
var inputs = document.getElementsByClassName('calculation-input')

var myResult = 0
for (let i = 0; i < inputs.length; i++) {
myResult += parseInt(inputs[i].value || 0, 10)
}

var asset = document.getElementById("asset");
asset.value = myResult;
}
<p class="a">
<label for="A">A</label>
<input
type="number"
class="calculation-input"
name="A"
id="A"
oninput="ass()"
placeholder="0"
/>
€<br />
</p>
<p class="a">
<label for="B">B</label>
<input
type="number"
class="calculation-input"
name="B"
id="B"
oninput="ass()"
placeholder="0"
min="0"
/>€<br />
</p>
<p class="a">
<label for="C">C</label>
<input
type="number"
class="calculation-input"
name="C"
id="C"
oninput="ass()"
min="0"
placeholder="0"
/>
€<br />
</p>

<h2>Your total assets are: </h2><output type="number" id="asset" name="asset"></output> €

How do I get the sum of three inputs values in a span using JavaScript or jQuery?

You can use each loop to iterate through your inputs and get required value from each inputs add them and then use $(".total-select").text(val); to same inside your span

Demo Code :

$("input[type=number]").change(function() {
var val = 0;
//loop through each inputs
$("input[type=number]").each(function() {
//sum values
val += parseInt($(this).val())
})
//put in span
$(".total-select").text(val);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="number" id="number1" name="1" min="0" max="8" value="0" />
<input type="number" id="number3" name="3" min="0" max="8" value="0" />
<input type="number" id="number2" name="2" min="0" max="8" value="0" />
<input type="number" id="number4" name="3" min="0" max="8" value="0" />
<span class="total-select" name="4">0</span>

Adding two numbers in javascript from two inputs in a form

You need to create addEventListener of calc button outside add(); and call add(); into event;

const btn = document.getElementById('btn');
const calc = document.getElementById('calc');

function add() {
const num1 = parseInt(document.getElementById('num1').value);
const num2 = parseInt(document.getElementById('num2').value);
const result = document.getElementById('result');
if (num1 && num2 !== NaN) {
let sum = num1 + num2;
result.value = sum;
return false;

} else {
alert("Enter Valid Number");
}
}
calc.addEventListener('click', () => {
add();
});
btn.addEventListener('click', () => {
num1.value = " ";
num2.value = " ";
result.value = " ";
});
<form id="adder" onsubmit="return add();">
<input type="text" name="num1" id='num1' placeholder="enter number">
<input type="text" name="num2" id='num2' placeholder="enter number">

<button id="calc" type="button">Add</button>
<input type="text" name="num3" id="result" readonly placeholder="Result">

<button type="button" id="btn">Clear</button>
</form>


Related Topics



Leave a reply



Submit