Hello I need to sum the values of same class input in one input with class name total.
<input type="text" class="qty1" value="" />
<input type="text" class="qty1" value="" />
<input type="text" class="qty1" value="" />
<input type="text" class="qty1" value="" />
<input type="text" class="qty1" value="" />
<input type="text" class="qty1" value="" />
<input type="text" class="total" value="" />
Possible?
A working fiddle here
$(document).on("change", "qty1", function() {
var sum = 0;
$("input[class *= 'qty1']").each(function(){
sum += +$(this).val();
});
$(".total").val(sum);
});
You pretty much had it, just needed to adjust your JQuery a little bit for the appropriate selectors
updated fiddle : http://jsfiddle.net/5gsBV/7/
$(document).on("change", ".qty1", function() {
var sum = 0;
$(".qty1").each(function(){
sum += +$(this).val();
});
$(".total").val(sum);
});
I suggest this solution:
html
<input type="text" class="qty1" value="" />
<input type="text" class="qty1" value="" />
<input type="text" class="qty1" value="" />
<input type="text" class="qty1" value="" />
<input type="text" class="qty1" value="" />
<input type="text" class="qty1" value="" />
<input type="text" class="total" value="" />
<div id="result"></div>
js
$(".qty1").on("blur", function(){
var sum=0;
$(".qty1").each(function(){
if($(this).val() !== "")
sum += parseInt($(this).val(), 10);
});
$("#result").html(sum);
});
fiddle
I think your issue is here:
$("#destination").val(sum);
change it to:
$(".total").val(sum);
And instead of change event i suggest you to use keyup instead.
$(document).on("keyup"
$(document).on("keyup", ".qty1", function() {
var sum = 0;
$(".qty1").each(function(){
sum += +$(this).val();
});
$(".total").val(sum);
});
We can use following own function
(function( $ ){
$.fn.sum=function () {
var sum=0;
$(this).each(function(index, element){
sum += parseFloat($(element).val());
});
return sum;
};
})( jQuery );
//Call $('.abcd').sum();
http://www.gleegrid.com/code-snippet/javascript/jquery-sum-input-values-by-class/?filter=bygroup&group=JQuery
$('.qty1').each(function(){
sum += parseFloat(this.value);
});
console.log(sum);
This will work with pure js
<input type="text" value=" " class="percent-input"> <br>
<input type="text" value=" " class="percent-input"> <br>
<input type="text" value=" " class="percent-input"> <br>
<p>Total Value :<span id="total">100%</span></p>
<p>Left Value :<span id="left">0.00%</span></p>
var percenInput = document.querySelectorAll('.percent-input');
for (let i = 0; i < percenInput.length; i++) {
percenInput[i].addEventListener('keyup', getPercentVal)
}
function getPercentVal() {
var total = 0;
var allPercentVal = document.querySelectorAll('.percent-input');
for (var i = 0; i < allPercentVal.length; i++) {
if (allPercentVal[i].value > 0) {
var ele = allPercentVal[i];
total += parseFloat(ele.value);
}
}
document.getElementById("total").innerHTML = total.toFixed(2) + '%';
document.getElementById("left").innerHTML = (100 - total).toFixed(2) + '%';
}
You almost had it:
$(document).on("change", ".qty1", function() {
var sum = 0;
$(".qty1").each(function(){
sum += +$(this).val();
});
$(".total").val(sum);
});
http://jsfiddle.net/DUKL6/1
The problem with all of the above answers is that they fail if you enter something other than a number. If you want something that is more friendly to users, you should do some validation, perhaps even give some feedback when a value other than a number is entered.
$('body').on('change', '.qty1', function() {
var total=0;
$(".qty1").each(function(){
quantity = parseInt($(this).val());
if (!isNaN(quantity)) {
total += quantity;
}
});
$('.total').val('Total: '+total);
});
<input type="text" class="price" placeholder="enter number one" />
<input type="text" class="price" placeholder="enter number two" />
<input type="text" class="price" placeholder="enter number three" />
<input type="text" class="price" placeholder="enter number four" />
<input type="text" id="total">
<script>
$(document).ready( function() {
$(document).on("keyup", ".price", function() {
var sum = 0;
$(".price").each(function(){
sum += +$(this).val();
});
$('#total').val(sum);
});
});
</script>
Related
I have some range sliders and input fields. From that I'm getting some equations now I want to subtract those dynamic numbers by their ID. Below is the code but I'm getting NaN value. Below the steps, I've done.
Getting #totalavgtime from the multiplication of range slider and .averagetime
Getting #timetoproduce from the multiplication of range slider and .radio-roi next input value.
Now trying to subtract #totalavgtime - #timetoproduce but getting NaN value in #timesaving.
$(document).ready(function() {
$(".range").on("change", function() {
var mult = 0;
$('.range').each(function(i) {
var selector_next = parseInt($(".averagetime:eq(" + i + ")").attr("value"))
mult += parseInt($(this).val()) * selector_next //multply..
console.log($(".averagetime:eq(" + i + ")").attr("value"), $(this).val())
})
$("#totalavgtime").val(mult)
})
});
$(document).ready(function() {
$('.range').on('change', function() {
let n = $(this).attr('id').match(/\d+/g)[0];
let total = 0;
let checkVal = $('.radio-roi:checked').next('input').val();
let multiplyFactor = parseFloat(checkVal);
console.log(multiplyFactor)
$('.range').each(function() {
total += (parseFloat($(this).val()) * multiplyFactor);
});
$('#timetoproduce').value(total);
})
});
$(document).ready(function() {
var txt1 = parseInt(document.getElementById("totalavgtime").value);
var txt2 = parseFloat(document.getElementById("timetoproduce").value);
var res = document.getElementById("timesaving");
Number(txt1);
Number(txt2);
//Substract that
res.value = txt1 - txt2;
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<input type="radio" id="" class="radio-roi" name="plan" value="plus" checked>
<input type="text" value="2.5" id="actualtime2" class="hiden-actual-time" disabled><br>
<input type="radio" id="" class="radio-roi" name="plan" value="pro">
<input type="text" value="3" id="actualtime3" class="hiden-actual-time" disabled><br>
<input type="text"value="6" id="avgtime-id" class="averagetime"disabled><br>
<input type="range" name="slider-1" min="0" max="12" value="0" step="1" class="range" id="range-slider"><br>
<input type="text"id="totalavgtime" value="" disabled><br>
<input type="text"id="timetoproduce" value="" disabled><br>
<input type="text"id="timesaving" value="" disabled><br>
You can merge both event handler in one as both are triggering same elements . So , inside this on each iteration get value of range slider and add total to same variable and set them in required input . Now , to subtract them check if the value is not null depending on this take value of input else take 0 to avoid NaN error.
Demo Code :
$(document).ready(function() {
$(".range").on("change", function() {
$(this).next().text($(this).val()) //for output(range)
var selector_next_avg = 0;
var timetoproduce = 0
var checkVal = parseFloat($('.radio-roi:checked').next('input').val()); //radio next input
$('.range').each(function(i) {
var selector_next = parseInt($(".averagetime:eq(" + i + ")").val()) //avg..input
selector_next_avg += parseInt($(this).val()) * selector_next;
timetoproduce += (parseFloat($(this).val()) * checkVal);
})
//set both values
$("#totalavgtime").val(selector_next_avg)
$('#timetoproduce').val(timetoproduce);
total() //call to total..(sub)
})
});
function total() {
var txt1 = $("#totalavgtime").val() != "" ? parseFloat($("#totalavgtime").val()) : 0; //if null take 0
var txt2 = $("#timetoproduce").val() != "" ? parseFloat($("#timetoproduce").val()) : 0;
$("#timesaving").val(txt1 - txt2); //set value
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<input type="radio" id="" class="radio-roi" name="plan" value="plus" checked>
<input type="text" value="2.5" id="actualtime2" class="hiden-actual-time" disabled><br>
<input type="radio" id="" class="radio-roi" name="plan" value="pro">
<input type="text" value="3" id="actualtime3" class="hiden-actual-time" disabled><br>
<input type="text" value="6" id="avgtime-id" class="averagetime" disabled><br>
<input type="range" name="slider-1" min="0" max="12" value="0" step="1" class="range" id="range-slider"><output></output><br>
<input type="text" id="totalavgtime" value="" disabled><br>
<input type="text" id="timetoproduce" value="" disabled><br>
<input type="text" id="timesaving" value="" disabled><br>
I have been working on this fiddle:
https://jsfiddle.net/j1vrb7to/165/
The code in that fiddle is this:
HTML:
<div id="CalculationContainer">
<input type="numbers" class="form-control new-tuition" /> <br />
<input type="numbers" class="form-control new-tuition" /> <br />
<input type="numbers" class="form-control new-tuition" /><br /><br />
<input type="numbers" id="new-tuition-total" disabled="disabled" /><br /> <br />
<input type="numbers" class="form-control new-state" /> <br />
<input type="numbers" class="form-control new-state" /> <br />
<input type="numbers" class="form-control new-state" /><br /><br />
<input type="numbers" id="new-state-total" disabled="disabled" />
</div>
JavaScript:
const NewTuitionInputs = document.querySelectorAll("div#CalculationContainer > input.new-tuition");
const NewStateInputs = document.querySelectorAll("div#CalculationContainer > input.new-state");
NewTuitionInputs.forEach(function(input) {
input.onchange = function() {
var total = 0;
NewTuitionInputs.forEach(function(input) {
total += parseInt(input.value);
});
document.getElementById("new-tuition-total").value = total;
}
});
NewStateInputs.forEach(function(input) {
input.onchange = function() {
var total = 0;
NewStateInputs.forEach(function(input) {
total += parseInt(input.value);
});
document.getElementById("new-state-total").value = total;
}
});
As the users enter values into the textboxes, I want to update the value of another field to display running totals. Ultimately I will need to keep track of 20+ running totals on my form. Instead of maintaining 20+ functions, is it possible to use a single function to calculate running totals on the fly? Here is some pseudocode to demonstrate what I'm thinking:
var ThisInput = document.querySelectorAll("div#CalculationContainer > input.[INPUT_CLASS_PARAMETER_HERE]");
ThisInput.forEach(function(input) {
input.onchange = function() {
var total = 0;
ThisInput.forEach(function(input) {
total += parseInt(input.value);
});
document.getElementById("[DYNAMICALLY_CHOOSE_WHERE_TO_DISPLAY").value = total;
}
});
You have a convention that the inputs have a class and then the total has an id with that class name plus -total. You can use this to your advantage in making a general purpose function:
function trackTotals(className){
var inputs = document.querySelectorAll(`div#CalculationContainer > input.${className}`);
inputs.forEach(input => {
input.addEventListener("change",()=>{
var total = [...inputs].reduce((acc,i) => acc + (parseInt(i.value,10) || 0),0);
document.getElementById(`${className}-total`).value = total;
})
})
}
Usage would then be:
trackTotals("new-tuition");
trackTotals("new-state");
// whatever else that follows same conventions
Live example follows:
trackTotals("new-tuition");
trackTotals("new-state");
function trackTotals(className){
var inputs = document.querySelectorAll(`div#CalculationContainer > input.${className}`);
inputs.forEach(input => {
input.addEventListener("change",()=>{
var total = [...inputs].reduce((acc,i) => acc + (parseInt(i.value,10) || 0),0);
document.getElementById(`${className}-total`).value = total;
})
})
}
<div id="CalculationContainer">
<input type="numbers" class="form-control new-tuition"/> <br/>
<input type="numbers" class="form-control new-tuition"/> <br/>
<input type="numbers" class="form-control new-tuition"/><br/><br/>
<input type="numbers" id="new-tuition-total" disabled="disabled"/><br /><br />
<input type="numbers" class="form-control new-state"/> <br/>
<input type="numbers" class="form-control new-state"/> <br/>
<input type="numbers" class="form-control new-state"/><br/><br/>
<input type="numbers" id="new-state-total" disabled="disabled"/>
</div>
Yes, you can create a function that takes the id:
function doTotal(name) {
var ThisInput = document.querySelectorAll(`div#CalculationContainer > input.${name}`);
ThisInput.forEach(function(input) {
input.onchange = function() {
var total = 0;
ThisInput.forEach(function(input) {
total += parseInt(input.value);
});
document.getElementById(`${name}-total`).value = total;
}
});
}
Note that I'm using string templates to build the selector strings.
You can use the event delegation method:
const calcContainer = document.getElementById('CalculationContainer')
, sumElms =
{ tuition: { sum: document.getElementById('new-tuition-total'), elms: [...document.querySelectorAll('input.new-tuition')] }
, state: { sum: document.getElementById('new-state-total'), elms: [...document.querySelectorAll('input.new-state')] }
}
;
calcContainer.oninput= ({target}) =>
{
if (!target.matches('.new-tuition, .new-state')) return
let sumElm = target.matches('.new-tuition') ? sumElms.tuition : sumElms.state
sumElm.sum.value = sumElm.elms.reduce((s,e)=>s+e.valueAsNumber,0)
}
#CalculationContainer input {
float: left;
clear:both;
width: 5em;
}
#CalculationContainer input:disabled {
margin-bottom: 1em;
font-weight: bold;
color:black;
}
<div id="CalculationContainer">
<input type="number" class="form-control new-tuition" value="0">
<input type="number" class="form-control new-tuition" value="0">
<input type="number" class="form-control new-tuition" value="0">
<input type="number" id="new-tuition-total" disabled="disabled" value="0">
<input type="number" class="form-control new-state" value="0">
<input type="number" class="form-control new-state"value="0">
<input type="number" class="form-control new-state"value="0">
<input type="number" id="new-state-total" disabled="disabled"value="0">
</div>
i want to show the money that customer must pay and my inputs are like this :
<input type="text" class="form-control" placeholder="cost " id="txt" name="credit">
<input type="text" class="form-control" placeholder="quantity" id="txt" name="limit">
when the input text is changing i want to show the total cost (quantity*cost) in a <p> tag Dynamicly how can it be with javascript?
You can try this:
<input type="text" class="form-control" placeholder="cost " id="credit" name="credit" onchange="calculate()">
<input type="text" class="form-control" placeholder="quantity" id="limit" name="limit" onchange="calculate()">
<p id="result"></p>
And javascript part:
function calculate() {
var cost = Number(document.getElementById("credit"));
var limit = Number(document.getElementById("limit"));
document.getElementById("result").innerHTML= cost*limit;
}
You must ensure you entered numbers in inputs.
All of the above will generate errors if both the boxes are blank . Try this code , its tested and running .
<script>
function calc()
{
var credit = document.getElementById("credit").value;
var limit = document.getElementById("limit").value;
if(credit == '' && limit != '')
{
document.getElementById("cost").innerHTML = parseInt(limit);
}
else if(limit == '' && credit != '')
{
document.getElementById("cost").innerHTML = parseInt(credit);
}
else if(limit!= '' && credit!= '')
{
document.getElementById("cost").innerHTML = parseInt(limit) * parseInt(credit);
}
else
{
document.getElementById("cost").innerHTML = '';
}
}
</script>
</head>
<input type="number" value="0" min="0" class="form-control" placeholder="cost" id="credit" name="credit" onkeyup="calc();">
<input type="number" value="0" min="0" class="form-control" placeholder="quantity" id="limit" name="limit" onkeyup="calc();">
<p id="cost"></p>
Hope this will be useful
// get cost field
var _cost = document.getElementById("cost");
_cost.addEventListener('keyup',function(event){
updateCost()
})
// get quantity field
var _quantity = document.getElementById("quantity");
_quantity.addEventListener('keyup',function(event){
updateCost()
})
function updateCost(){
var _getCost = document.getElementById("cost").value;
var _getQuantity = document.getElementById("quantity").value;
var _total = _getCost*_getQuantity;
console.log(_total);
document.getElementById("updateValue").textContent = ""; // Erase previous value
document.getElementById("updateValue").textContent = _total // update with new value
}
jsfiddle
In case you consider using JQuery I've made this fiddle.
See if it works for you.
https://fiddle.jshell.net/9cpbdegt/
$(document).ready(function() {
$('#credit').keyup(function() {
recalc();
});
$('#limit').keyup(function() {
recalc();
});
function recalc() {
var credit = $("#credit").val();
var limit = $("#limit").val();
var result = credit * limit;
$("#result").text(result);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" class="form-control" placeholder="cost " id="credit" name="credit" value="0">x
<input type="text" class="form-control" placeholder="quantity" id="limit" name="limit" value="0">
<p id="result">0</p>
Try this:
<script >
function myFunction() {
document.getElementById('totalcost').innerHTML = document.getElementById('txt').value * document.getElementById('txt2').value;}
</script>
Also, change your HTML to this:
<input type="text" onkeypress="myFunction()" onkeyup="myFunction()" onclick="myFunction()" onmousemove="myFunction()" class="form-control" placeholder="cost " id="txt" name="credit">
<input type="text" onkeypress="myFunction()" onkeyup="myFunction()" onclick="myFunction()" onmousemove="myFunction()" class="form-control" placeholder="quantity" id="txt2" name="limit">
Enter cost and quantity.
Note the change with the second input: id='txt' was changed to id='txt2'. This is because no 2 elements can have the same id.
Note: Untested.
I have 3 inputs and I'm trying to get the sum of the numbers each time a user updates one of them.
HTML
<input class="my-input" type="number" name="" value="0" min="0">
<input class="my-input" type="number" name="" value="0" min="0">
<input class="my-input" type="number" name="" value="0" min="0">
JS
var sum = 0;
$('.my-input').each(function(index, elem){
var value = $(this).val();
sum += parseFloat($(elem).val());
console.log(sum);
$(this).on('keyup click', function (){
sum += parseFloat($(elem).val());
});
});
But I keep getting crazy results..
EDIT:
I tried this:
function getSum(){
var sum = 0;
$('.my-input').each(function(index, elem){
var value = $(this).val();
sum += parseFloat($(elem).val());
});
return sum;
}
$('.my-input').each(function(){
$(this).on('keyup click', function(){
console.log( this.value );
var curSum = getSum();
console.log('current sum: ' + curSum);
});
});
Consider this example:
<input class="my-input" type="number" name="" value="0" min="0" />
<input class="my-input" type="number" name="" value="0" min="0" />
<input class="my-input" type="number" name="" value="0" min="0" />
<input type="text" id="total" value="" />
<script type="text/javascript">
// just get keyup event
$('.my-input').on('keyup', function(){
var total = 0;
// on every keyup, loop all the elements and add all the results
$('.my-input').each(function(index, element) {
var val = parseFloat($(element).val());
if( !isNaN( val )){
total += val;
}
});
$('#total').val(total);
});
</script>
Hi I'm new for programming and I'm facing one problem.
I have 3 input for values and 1 input for total. What I need is when I change the value in any input total should change automatically.
<input type="text" name="Amt" id="amount" class="form-control" />
<input type="text" name="Amt" id="amount" class="form-control" />
<input type="text" name="Amt" id="amount" class="form-control" />
And for total I have:
<input type="text" class="form-control" name="total" id="total" value="" />
And below is the script:
<script type="text/javascript">
$('#amount').change(function() {
$('#total').attr('value', function() {
var result = 0;
$('#amount').each(function() {
result += $(this).attr('value');
});
return result;
});
});
</script>
You have multiple ids for amount. These should be changed to classes. In addition, the value for each amount will be picked out by jQuery as a string, so that needs to be changed to an integer:
$('.amount').change(function () {
var result = 0;
$('.amount').each(function () {
result += +$(this).val();
});
$('#total').val(result);
});
Fiddle.