Calculate sum and multiply its value - javascript

I'm calculating the sum of a and b and putting it in text box named sum.
After I enter a number in number text box, it should calculate the final = sum * number.
<input type="text" class="txt_1_0" name="a" />
<input type="text" class="txt_1_0" name="b" />
<input type="text" id="sum" name="sum" />
<input type="text" class="number" name="number" />
<input type="text" class="final" name="final" />
I tried the following:
$(document).ready(function() {
$(".txt_1_0").change(function() {
var total = 0.00;
var textbox3 = 0.00; // this gonna be your third textbox
$(".txt_1_0").each(function() {
total += parseFloat(this.value) / 5;
});
textbox3 = $("#sum").val((total).toFixed(2));
});
});
How do I get the number value and calculate final?

You haven't actually added any function that would do the final calculation. So to multiply the sum (subtotal) with number, do the following:
$(".number").change(function () {
var final = $("#sum").val() * $(this).val();
$('.final').val(final);
});
Here is a demo - note that I have removed the division by 5 from your previous function as it didn't make sense from the the way your question was asked.

Or you can use keyup event with this jQuery code Fiddle
<script type="text/javascript">
$(document).ready(function(){
$('input[type="text"]').on('keyup',function(){
var a=parseFloat($('.txt_1_0:first').val())
var b=parseFloat($('.txt_1_0:last').val())
if(a && b){$('#sum').val(a+b)}
var number=$('.number').val()
if(number){
$('.final').val($('#sum').val()*number)
}
})
})
</script>

Related

Can't get the value from input type number

I'm trying to get the input values from the "min_num" and "max_num" fields but there's nothing there. Also when I try the parseInt() method I get not a number (NaN)...
How do I solve this?
var min_num = document.getElementById("min_num").value;
var max_num = document.getElementById("max_num").value;
var generate = document.getElementById("generate");
function myRandomNumber(min, max) {
var randomNumber = Math.floor(Math.random() * max) + min;
document.getElementById("random_number").value = randomNumber;
}
generate.onclick = myRandomNumber(min_num, max_num);
<form action="#">
<input type="number" id="min_num" placeholder="Minimum number">
<input type="number" id="max_num" placeholder="Maximum number"><br>
<input type="text" id="random_number" disabled="disabled" placeholder="Random number">
<button id="generate">Generate</button>
</form>
You have 4 problems:
You read the value on page load. The value does not update, it is read that that moment in time and store.
You call a function and what it returns is stored to the event listener
You are working with strings and not numbers. You need to convert the value to a number.
You are not generating a random number in a range like you think you are. It can generate a number that will be greater than the max.
var min_num = document.getElementById("min_num"); // do not read the value
var max_num = document.getElementById("max_num");
var generate = document.getElementById("generate");
function myRandomNumber(min, max) {
var randomNumber = Math.floor(Math.random() * (max - min + 1)) + min; // need to subtract the min
document.getElementById("random_number").value = randomNumber;
}
generate.addEventListener("click", function() { // not calling the function
myRandomNumber(+min_num.value, +max_num.value); // reading the value and converting it to a number
});
<form>
<input type="number" id="min_num" placeholder="Minimum number">
<input type="number" id="max_num" placeholder="Maximum number"><br>
<input type="text" id="random_number" disabled="disabled" placeholder="Random number">
<button type="button" id="generate">Generate</button>
</form>

How to sum up all dynamic inputs in js

How can I get all the sum of these inputs? Sometime they have a value from the database, sometimes no value and needs to be inputted. I'm using jquery for this.
Please see the code below:
$(document).ready(function(){
$('input[name=grade\\[\\]]').on('focus, keyup', function(){
var points = $('input[name=grade\\[\\]]');
var totals = points.get()
.map(function(sel){
return parseFloat(sel.value, 10);
})
.reduce(getSum, 0);
if(points.length == 1){
$('input[name=total]').val($(this).val());
} else if(points.length > 1 && totals < 100){
$('input[name=total]').val(totals);
}
});
function getSum(total, value){
return total + parseFloat(value, 10);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<input type="text" name="grade[]" ><br><br>
<input type="text" name="grade[]" ><br><br>
<input type="text" name="grade[]" ><br><br>
<input type="text" name="grade[]" ><br><br>
<input type="text" name="grade[]" ><br><br><br>
Total<br>
<input type="text" name="total" readonly>
</form>
The problem is that parseFloat() returns NaN when the value can't be parsed as a number, and the result of adding up a list that includes some NaN values will be NaN. Which means your if/else that decides whether to display the total won't display it because NaN < 100 is false.
Given that your inputs are empty to start with those items are parsed as NaN.
The simplest fix is to change this line in your .map() function:
return parseFloat(sel.value, 10);
to be:
return parseFloat(sel.value) || 0;
...where the || operator will return the left-hand operand if it is a truthy value, i.e., a number, not NaN or 0, and otherwise return the right-hand operand 0. That is, blank or otherwise non-numeric values will be treated as if they were 0.
You don't need to call parseFloat() again in your getSum() function, because by then you already have numbers.
(Note also that parseFloat() doesn't take a second argument, you've mixed that up with parseInt().)
$(document).ready(function() {
$('input[name=grade\\[\\]]').on('focus, keyup', function() {
var points = $('input[name=grade\\[\\]]');
var totals = points.get()
.map(function(sel) {
return parseFloat(sel.value) || 0; // <-- this is the line that changed
})
.reduce(getSum, 0);
if (points.length == 1) {
$('input[name=total]').val($(this).val());
} else if (points.length > 1 && totals < 100) {
$('input[name=total]').val(totals);
}
});
function getSum(total, value) {
return total + value; // <-- no need for parseFloat() here
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<input type="text" name="grade[]">
<input type="text" name="grade[]">
<input type="text" name="grade[]">
<input type="text" name="grade[]">
<input type="text" name="grade[]"><br><br><br> Total
<br>
<input type="text" name="total" readonly>
</form>
(I've removed most of the <br> elements just to avoid having to scroll down to see the total for demo purposes.)

Adding two input boxes using Javascript

I am trying to add two already calculated and formatted input fields and not having much luck. My code is:
<input type='text' id='cage_linear_feet' value='83'>
<input type='text' id='cage_estimate' disabled>
<br>
<input type='text' id='cage_doors' value='3'>
<input type='text' id='doors_estimate' disabled>
<br>
<input type='text' id='cage_totals' disabled>
<script>
function format(n) {
return n.toFixed(2).replace(/(\d)(?=(\d{3})+\.)/g, "$1,");
}
//Linear Feet Calculation
$(document).ready(LinearFeet);
document.getElementById('cage_linear_feet').addEventListener("keyup", LinearFeet);
var inputBox1 = document.getElementById('cage_linear_feet');
function LinearFeet(){
document.getElementById('cage_estimate').value = format(inputBox1.value*225);
}
//Doors Calculation
$(document).ready(CageDoors);
document.getElementById('cage_doors').addEventListener("keyup", CageDoors);
var inputBox2 = document.getElementById('cage_doors');
function CageDoors(){
document.getElementById('doors_estimate').value = format(inputBox2.value*1800);
}
</script>
How do I add cage_estimate and doors_estimate together and display in cage_totals in real time?
Thanks,
John
This is what you are asking
how to convert comma separated currency into number in java script
parseFloat
This function calculate total. You have to call it in each key functions.
function setTotal(){
var x=document.getElementById('doors_estimate').value;
var y=document.getElementById('cage_estimate').value;
if(x ){
if(y){
var z=(parseFloat(x.replace(',',''))+parseFloat(y.replace(',','')));
document.getElementById('cage_totals').value=format(z);
}
}
}
calling codes
function LinearFeet(){
var inputBox1 = document.getElementById('cage_linear_feet');
document.getElementById('cage_estimate').value = format(inputBox1.value*225);
setTotal();
}
function CageDoors(){
var inputBox2 = document.getElementById('cage_doors');
document.getElementById('doors_estimate').value = format(inputBox2.value*1800);
setTotal();
}
Referances:
parseFloat
replace

Simple JavaScript function returns function and not value

I'm just starting out and I'm trying to build a simple calculation function that will display the result of 2 numbers on a page. When the submit button is hit the output is the function and not the value. Where have I gone wrong?
HTML
<div id="input">
<form id="start">
<input id="price" type="number" placeholder="What is the starting price?" value="10">
<input id="tax" type="number" value="0.08" step="0.005">
</form>
<button type="button" form="start" value="submit" onClick="total()">Submit</button>
</div>
<div id="test">Test</div>
JS
<script>
'use strict';
var total = function() {
var price = function() {
parseFloat(document.getElementById("price"));
}
var tax = function() {
parseFloat(document.getElementById("tax"));
}
var final = function() {
final = price * tax;
final = total
}
document.getElementById("output").innerHTML = final;
};
</script>
You have several issues with your javascript. Let's break them down one by one:
var price = function() {
parseFloat(document.getElementById("price"));
}
document.getElementById returns an element. parseFloat would try to calculate the element, and not the value in this case (Which would always be NaN or Not a Number). You want the value of this element, so using .value will return the value. Furthermore, you're not actually doing anything with the value. (You should use return to return the float found, or set it to another variable.)
var final = function() {
final = price * tax;
final = total
}
price and tax are both functions in this case. You can't simply multiply them to get your desired result. Using var total = price() * tax(); will set the variable total to the float returned from price() and tax() now. Returning this value to the function will fix the next line:
document.getElementById("output").innerHTML = final;
final here is also a function. You want to call it by using final().
Your final script:
var total = function() {
var price = function() {
return parseFloat(document.getElementById("price").value);
}
var tax = function() {
return parseFloat(document.getElementById("tax").value);
}
var final = function() {
var total = price() * tax();
return total
}
document.getElementById("output").innerHTML = final();
};
<div id="input">
<form id="start">
<input id="price" type="number" placeholder="What is the starting price?" value="10">
<input id="tax" type="number" value="0.08" step="0.005">
</form>
<button type="button" form="start" value="submit" onClick="total()">Submit</button>
</div>
<div id="output">test</div>
You have several issues, you put some code into function without calling them.
Another problem is, you need the value of the input tags.
'use strict';
var total = function() {
var price = parseFloat(document.getElementById("price").value);
// get value ^^^^^^
var tax = parseFloat(document.getElementById("tax").value)
// get value ^^^^^^
// calculate directly the final value
var final = price * tax;
document.getElementById("output").innerHTML = final;
};
<div id="input">
<form id="start">
<input id="price" type="number" placeholder="What is the starting price?" value="10">
<input id="tax" type="number" value="0.08" step="0.005">
</form>
<button type="button" form="start" value="submit" onClick="total()">Submit</button>
<div id="output"></div>
Delete
var final = function() {
final = price * tax;
final = total
}
and instead put
return price * tax;

Sum up all text boxes with a particular class name?

I have a grid, with one of the columns containing a textbox, where a user can type in a dollar amount. The text boxes are declared as:
<input class="change-handled" sub-category-id="83" data-id="" style="text-align: right; width: 100%" type="number" value="">
Some are all decorated with the class "change-handled".
What I need to do, is, using javascript/jquery, sum up all the boxes which are using that class, and display the total elsewhere on the screen.
How can I have a global event, that would allow this to occur when ever I exit one of the boxes (i.e: Tab out, or ENTER out).
At the moment, I have an event which doesn't do much at the moment, which will be used:
$('body').on('change', 'input.change-handled', SaveData);
function SaveData() {
var dataId = $(this).attr('data-id');
var categoryId = $(this).attr('sub-category-id');
var value = $(this).val();
}
How can I use that SaveData event, to find all the editboxes with the 'change-handled' class, sum up their values, and display it somewhere?
In plain JavaScript:
var changeHandled = [].slice.call(document.querySelectorAll('.change-handled'));
var total = document.querySelector('.total');
function calc() {
total.textContent = changeHandled.reduce(function(total, el) {
return total += Number(el.value);
}, 0);
}
changeHandled.forEach(function(el) {
el.onblur = calc;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="number" class="change-handled">
<input type="number" class="change-handled">
<input type="number" class="change-handled">
Total: $<span class="total">0</span>
I think what you're looking for is the blur event.
$('body').on('blur', 'input.change-handled', UpdateTotal);
function UpdateTotal() {
var total = 0;
var $changeInputs = $('input.change-handled');
$changeInputs.each(function(idx, el) {
total += Number($(el).val());
});
$('.total').text(total);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="number" class="change-handled">
<input type="number" class="change-handled">
<input type="number" class="change-handled">
Total: $<span class="total">0</span>
Here's how you can sum up the values:
var total = 0;
$(".change-handled").each(function(index, box) {
total += parseInt($(box).val(), 10);
});
You would then display them by using the text or html functions provided by jQuery on elements.
This can be used from anywhere in your code, including the event handler.

Categories

Resources