I have a simple calculator. What I want to get is to show 0 value when calculations value is negative.
Here is the code:
$("#button").click(function() {
var total = 0.0;
$.each($(".amount"), function() {
var amount = parseFloat($(this).val() || 0);
var multiply = parseFloat($(".multiply").val());
if (amount && multiply)
total += amount * multiply;
});
$.each($(".summable"), function() {
total += parseInt($(this).val() || 0);
});
$.each($(".minusable"), function() {
total -= parseInt($(this).val() || 0);
});
$("#sum").val(total.toFixed(2))
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.0/jquery.min.js"></script>
Amount
<input type="text" class="amount" />
<br>
<select class="multiply">
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
</select>
<br>Sum 1
<input type="text" class="summable" />
<br>Sum 2
<input type="text" class="summable" />
<br>Minus 1
<input type="text" class="minusable" />
<br>Minus 2
<input type="text" class="minusable" />
<br>
<input id="sum" type="text" />
<button id="button">Click Me</button>
Simply enter Minus values greater than Amount and Sum. You will get negative value as a result. Please point me how to show "0" when the result value is negative.
Thanks in advance.
You can also use Math.max(), it'll return 0 if the other value is negative:
$("#sum").val( Math.max( total, 0 ).toFixed(2) );
Just add another small thing:
if (total.toFixed(2) > 0)
$("#sum").val(total.toFixed(2));
else
$("#sum").val("0");
Snippet:
$("#button").click(function() {
var total = 0.0;
$.each($(".amount"), function() {
var amount = parseFloat($(this).val() || 0);
var multiply = parseFloat($(".multiply").val());
if (amount && multiply)
total += amount * multiply;
});
$.each($(".summable"), function() {
total += parseInt($(this).val() || 0);
});
$.each($(".minusable"), function() {
total -= parseInt($(this).val() || 0);
});
if (total.toFixed(2) > 0)
$("#sum").val(total.toFixed(2));
else
$("#sum").val("0");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.0/jquery.min.js"></script>
Amount
<input type="text" class="amount" />
<br>
<select class="multiply">
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
</select>
<br>Sum 1
<input type="text" class="summable" />
<br>Sum 2
<input type="text" class="summable" />
<br>Minus 1
<input type="text" class="minusable" />
<br>Minus 2
<input type="text" class="minusable" />
<br>
<input id="sum" type="text" />
<button id="button">Click Me</button>
This will check if the value is positive, if not then use 0.
$("#sum").val(total > 0 ? total.toFixed(2) : 0);
Ternary Operator
Just check in an if if the total is less than 0 if so set the total to 0.
$("#button").click(function() {
var total = 0.0;
$.each($(".amount"), function() {
var amount = parseFloat($(this).val() || 0);
var multiply = parseFloat($(".multiply").val());
if (amount && multiply)
total += amount * multiply;
});
$.each($(".summable"), function() {
total += parseInt($(this).val() || 0);
});
$.each($(".minusable"), function() {
total -= parseInt($(this).val() || 0);
if(total<0)
total=0;
});
$("#sum").val(total.toFixed(2))
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.0/jquery.min.js"></script>
Amount
<input type="text" class="amount" />
<br>
<select class="multiply">
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
</select>
<br>Sum 1
<input type="text" class="summable" />
<br>Sum 2
<input type="text" class="summable" />
<br>Minus 1
<input type="text" class="minusable" />
<br>Minus 2
<input type="text" class="minusable" />
<br>
<input id="sum" type="text" />
<button id="button">Click Me</button>
$("#button").click(function() {
var total = 0.0;
$.each($(".amount"), function() {
var amount = parseFloat($(this).val() || 0);
var multiply = parseFloat($(".multiply").val());
if (amount && multiply)
total += amount * multiply;
});
$.each($(".summable"), function() {
total += parseInt($(this).val() || 0);
});
$.each($(".minusable"), function() {
total -= parseInt($(this).val() || 0);
});
if(total < 0){
total = 0;
}
$("#sum").val(total.toFixed(2))
});
Related
I am working on a payroll project in which I want to calculate overtime, allowance and tax to salary. I want to add overtime and allowance to salary and subtract tax from salary.
The following script works with overtime and allowance but I'm facing problems with calculating tax.
When I enter a tax percentage it should calculate the tax amount from the salary to the tax field and calculate the total. When I enter the tax directly it should calculate the percentage to the taxPercentage field and calculate the total.
$(document).on('change keyup blur', '.add', function(e) {
add();
});
function add() {
salary = $('#salary').val();
allowance = $('#allowance').val() || 0;
over = $('#over').val() || 0;
prevTotal = $('#total').val() || 9000;
if (allowance > 0 || over > 0) {
total = parseFloat(salary) + parseFloat(allowance) + parseFloat(over);
$('#total').val(total);
} else {
$('#total').val(prevTotal);
}
}
$(document).on('change keyup blur', '.tax', function(e) {
subtracttax();
});
function subtracttax() {
salary = $('#salary').val();
taxPercentage = $('#taxPercentage').val() || 0;
tax = $('#tax').val() || 0;
prevTotal = $('#total').val() || 9000;
if (taxPercentage > 0) {
total = parseFloat(salary) * parseFloat(taxPercentage) / 100;
$('#tax').val(total);
$('#total').val(prevTotal - total);
} else {
$('#total').val(prevTotal);
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>
<div>
<label> salary </label>
<input type="text" id="salary" value="9000" />
</div>
<br>
<div>
<label> over Time </label>
<input type="text" class="add" id="over" />
</div>
<br>
<div>
<label> allowance </label>
<input type="text" class="add" id="allowance" />
</div>
<br>
<div>
<label> Tax Percentage</label>
<input type="text" class="tax" id="taxPercentage" />
</div>
<br>
<div>
<label> Total Tax</label>
<input type="text" class="tax" id="tax" />
</div>
<br>
<div>
<label> Total salary</label>
<input type="text" id="total" />
</div>
Try like this.
as per your comment I only added salary + over time.
calculateTax();
$(document).on('change keyup blur', '.tax', function(e) {
calculateTax();
});
$(document).on('change keyup blur', '.taxVal', function(e) {
calculateTaxPer();
});
function calculateTax() {
salary = $('#salary').val();
allowance = $('#allowance').val() || 0;
over = $('#over').val() || 0;
total = (parseFloat(salary) + parseFloat(allowance) + parseFloat(over)) || 0;
taxPercentage = $('#taxPercentage').val() || 0;
tax = $('#tax').val() || 0;
$('#total').val(total);
if (taxPercentage > 0) {
totalTax = (parseFloat(salary) + parseFloat(over)) * parseFloat(taxPercentage) / 100;
$('#tax').val(totalTax);
$('#total').val(total - totalTax);
return false;
}
}
function calculateTaxPer(){
salary = $('#salary').val();
allowance = $('#allowance').val() || 0;
over = $('#over').val() || 0;
total = (parseFloat(salary) + parseFloat(allowance) + parseFloat(over)) || 0;
taxPercentage = $('#taxPercentage').val() || 0;
tax = $('#tax').val() || 0;
$('#total').val(total);
if(tax > 0){
taxPer = (parseFloat(tax)/(parseFloat(salary) + parseFloat(over)))*100;
$('#taxPercentage').val(taxPer);
$('#total').val(total - tax);
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>
<div>
<label> salary </label>
<input type="text" id="salary" value="9000" />
</div>
<br>
<div>
<label> over Time </label>
<input type="text" class="tax" id="over" />
</div>
<br>
<div>
<label> allowance </label>
<input type="text" class="tax" id="allowance" />
</div>
<br>
<div>
<label> Tax Percentage</label>
<input type="text" class="tax" id="taxPercentage" />
</div>
<br>
<div>
<label> Total Tax</label>
<input type="text" class="taxVal" id="tax" />
</div>
<br>
<div>
<label> Total salary</label>
<input type="text" id="total" />
</div>
change this line in subtracttax function
prevTotal = $('#total').val() || 9000;
to
prevTotal = parseFloat(salary) + parseFloat(allowance) + parseFloat(over);
Problem is you are overriding the total value once the tax value is entered. Instead you should calculate totals each time you make changes.
Good evening! I've created a mean calculator and I would also like to add median function to it. I've attempted to create it but it isn't very successful. Please help! Here is the code I have for the average:
"<fieldset id="numbers"><legend>Numbers</legend>
First number: <input type="number" onkeyup="getTotal();" onchange="getTotal();" /><br/>
Second number: <input type="number" onkeyup="getTotal();" onchange="getTotal();" /><br/>
Third number: <input type="number" onkeyup="getTotal();" onchange="getTotal();" /><br/>
Fourth number: <input type="number" onkeyup="getTotal();" onchange="getTotal();" /><br/>
Fifth number: <input type="number" onkeyup="getTotal();" onchange="getTotal();" />
</fieldset>
<div id="average">Average: --</div>
<script type="text/javascript">
function getTotal() {
var inputs = document.getElementById('numbers').getElementsByTagName('input'),
count = inputs.length, i, total = 0;
for( i=0; i<count; i++) total += parseInt(inputs[i].value || "0",10);
document.getElementById('average').firstChild.nodeValue = "Average: "+(total/count);
}"
Here is all of my code.
<select id="operator">
<option value="-">Subtract</option>
<option value="+">Add</option>
<option value="*">Multiply</option>
<option value="/">Divide</option>
</select>
<h3>Calculator</h3>
1st Number: <input id="x" data-in="" type="text" /><br>2nd Number:
<input id="y" data-in="" type="text" br>
<hr>Answer:
<div id="d"></div>
<SCRIPT language="JavaScript">
var x = document.getElementById("x");
var y = document.getElementById("y");
var d = document.getElementById("d");
var xstored = x.getAttribute("data-in");
var ystored = y.getAttribute("data-in");
setInterval(function(){
if( x == document.activeElement ){
var temp = x.value;
if( xstored != temp ){
xstored = temp;
x.setAttribute("data-in",temp);
calculate();
}
}
if( y == document.activeElement ){
var temp = y.value;
if( ystored != temp ){
ystored = temp;
y.setAttribute("data-in",temp);
calculate();
}
}
},50);
function calculate() {
var operator = document.getElementById('operator').value;
var value = eval(x.value + operator + y.value);
d.innerHTML = value;
}
x.onblur = calculate;
calculate();
</SCRIPT>
<hr>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
</head>
<body>
<h3>Backround Color</h3>
<select runat="server" id="select">
<option value="A" style="background-color: white;">White</option>
<option value="B" style="background-color: black;">Black</option>
<option value="C" style="background-color: yellow;">Yellow</option>
<option value="D" style="background-color: green;">Green</option>
<option value="E" style="background-color: blue;">Blue</option>
<option value="F" style="background-color: red;">Red</option>
<option value="G" style="background-color: purple;">Purple</option>
<option value="H" style="background-color: orange;">Orange</option>
<option value="I" style="background-color: brown;">Brown</option>
<option value="J" style="background-color: pink;">Pink</option>
<option value="K" style="background-color: cyan;">Cyan</option>
<option value="L" style="background-color: gray;">Gray</option>
</select>
<script>
$('#select').change(function(){
if($(this).val() == 'A'){
$("body").css('background-color', 'white');
}
if($(this).val() == 'B'){
$("body").css('background-color', 'black');
}
if($(this).val() == 'C'){
$("body").css('background-color', 'yellow');
}
if($(this).val() == 'D'){
$("body").css('background-color', 'green');
}
if($(this).val() == 'E'){
$("body").css('background-color', 'blue');
}
if($(this).val() == 'F'){
$("body").css('background-color', 'red');
}
if($(this).val() == 'G'){
$("body").css('background-color', 'purple');
}
if($(this).val() == 'H'){
$("body").css('background-color', 'orange');
}
if($(this).val() == 'I'){
$("body").css('background-color', 'brown');
}
if($(this).val() == 'J'){
$("body").css('background-color', 'pink');
}
if($(this).val() == 'K'){
$("body").css('background-color', 'cyan');
}
if($(this).val() == 'L'){
$("body").css('background-color', 'gray');
}
});
</script>
</body>
</html>
<hr>
<fieldset id="numbers"><legend>Numbers</legend>
First number: <input type="number" onkeyup="getTotal();" onchange="getTotal();" /><br/>
Second number: <input type="number" onkeyup="getTotal();" onchange="getTotal();" /><br/>
Third number: <input type="number" onkeyup="getTotal();" onchange="getTotal();" /><br/>
Fourth number: <input type="number" onkeyup="getTotal();" onchange="getTotal();" /><br/>
Fifth number: <input type="number" onkeyup="getTotal();" onchange="getTotal();" />
</fieldset>
<div id="average">Average: --</div>
<script type="text/javascript">
function getTotal() {
var inputs = document.getElementById('numbers').getElementsByTagName('input'),
count = inputs.length, i, total = 0;
for( i=0; i<count; i++) total += parseInt(inputs[i].value || "0",10);
document.getElementById('average').firstChild.nodeValue = "Average: "+(total/count);
}
</script>
Working JsBin
Function to find the median of an array:
function median(arr) {
arr.sort( function(a,b) {return a - b;} );
var mid = Math.floor(arr.length/2);
if(arr.length % 2) {
return arr[mid];
}
else {
return (arr[mid-1] + arr[mid]) / 2;
}
}
I have more than 10 section that included three inputs in each section as follows:
<div class="product_quantity">
<div class="color-quantity">
<input onkeydown="return myFunction(event);" name="custom_small" class="custom_small" type="text">
<input onkeydown="return myFunction(event);" name="custom_medium" class="custom_medium" type="text">
<input onkeydown="return myFunction(event);" name="custom_large" class="custom_large" type="text">
</div>
<div class="color-quantity">
<input onkeydown="return myFunction(event);" name="white_small" class="custom_small" type="text">
<input onkeydown="return myFunction(event);" name="white_medium" class="custom_medium" type="text">
<input onkeydown="return myFunction(event);" name="white_large" class="custom_large" type="text">
</div>
</div>
I am calculating the product quantity from each section but its giving me the whole amount of products on the basis of amount entered in every input. but i want the amount of products in section separately
I am using jQuery to do so please check the code and recommend the changes as required:
jQuery(".color-quantity input").each(function () {
if (this.value) {
quantity += (this.value) * 1;
classname = jQuery(this).attr('class');
arr.push(classname);
}
if (quantity == '') {
quantity = 0;
}
});
You can get total off each section as an array like following.
var arr = $('.color-quantity').map(function () {
var total = 0;
$('input', this).each(function () {
total += this.value * 1;
});
//do some stuff
if (total < 50) {
$('.btn-cart').removeAttr("onclick");
}
return total;
}).get();
console.log(arr)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="color-quantity">
<input type="text" value="1">
<input type="text" value="2">
<input type="text" value="3">
</div>
<div class="color-quantity">
<input type="text" value="4">
<input type="text" value="5">
<input type="text" value="6">
</div>
You might try a nested loop. first loop through the color-quantity divs, then through the inputs. like this:
jQuery(".color-quantity").each(function () {
var quantity = 0;
$(this).find('input').each(function() {
if (this.value) {
quantity += (this.value) * 1;
classname = jQuery(this).attr('class');
arr.push(classname);
}
if (quantity == '') {
quantity = 0;
}
});
// here is where you can get the total value for each div
});
So basically, I am creating an application form for gym membership.
The base cost is $100. If juggling is selected, the cost will increase by $50.
Also, the base cost will increase by $50 if the 'BMI' is > 25 and <= 30. If the 'BMI' is > 30, it will increase by $100 instead.
This is my code. It is not working as intended. Would like some help. Thanks a lot.
<!DOCTYPE html>
<html>
<head>
<title>UWS application form</title>
<link rel="stylesheet" href="Prac1Task2.css" />
</head>
<body>
<form>
<fieldset>
<legend>Fitness Details</legend>
Favourite Activities: <br/>
<input type="checkbox" name="activity" value="cycling" id="cycling"><label for="cycling">Cycling</label>
<input type="checkbox" name="activity" value="50" id="juggling" onchange="update(this);"><label for="juggling">Juggling</label>
<br/>
<br/>
<label for="height">What is your height (Meters)</label><br/>
<input type="number" name="height" id="height" class="input" onchange="getBMI()">
<br/>
<label for="weight">What is your weight? (kg)</label><br/>
<input type="number" name="weight" id="weight" class="input" onchange="getBMI()">
<br/>
<label for="bmi">BMI:</label><br/>
<input type="number" name="bmi" id="bmi" class="input" value="" readonly>
<script>
function getBMI()
{
var height = document.getElementById("height").value;
var weight = document.getElementById("weight").value;
document.getElementById("bmi").value = (weight / height) / height;
var bmi = document.getElementById("bmi");
var price = document.getElementById("price").value;
if (bmi.value > 25 && bmi.value <= 30)
{
parseInt(price.value) += parseInt(50);
document.getElementById('price').value = price.value;
}
else if (bmi.value > 30)
{
document.getElementById("price").value = document.getElementById("price").value + 100;
}
}
</script>
</fieldset>
<br/>
<fieldset>
<legend>Application Details</legend>
Date of Application:<br/>
<input class="input" id="date" name="date" readonly />
<script>
var timetime = new Date();
document.getElementById("date").value = (timetime.getDate() + "/" + (timetime.getMonth() + 1)
+ "/" + timetime.getFullYear());
</script>
<br/><br/>
Cost of Application: <br/>
$<input type="number" class="input" id="price" name="price" step="0.01" value="100" readonly />
<script>
var total = 100;
function update(feature) {
if(feature.checked == true){
total += parseInt(feature.value);
document.getElementById('price').value = total;
}
if(feature.checked == false){
total -= parseInt(feature.value);
document.getElementById('price').value = total;
}
}
</script>
</fieldset>
<br/>
<input type="submit" value="Submit" class="button">
</form>
</body>
</html>
You haven't mentioned the exact issue which you are facing. However, I think there should be some problem with this line of code.
parseInt(price.value) += parseInt(50);
parseInt() is a function and you cannot assign values to it.
It should be some thing like this
price.value = parseInt(price.value) + parseInt(50);
Also price.value is not a proper reference because you are assigning document.getElementById("price").value; to it. So you should be using price instead of price.value
I have this short form that when the user selects the first option in a dropdown menu, three fields will appear. The first field has a default value while the other two should be fill up by the user. Then I need to get the total of the three fields. If the user selcts the second option, the three fields will not appear. As of now, this is what I've got:
HTML
<select id="select1">
<option value="A">New</option>
<option value="B>Satisfied</option>
</select>
<div id="d1>
<label>This is a default value</label><input type="text" id="input1" placeholder="$75,000" style="width: 100px;"/>
<label>Preferred Value:</label><input type="text" id="input2" value="" style="width: 100px;"/>
<label>Number of Contributors:</label><input type="text" id="input3" value="" style="width: 100px;"/>
<label>Total:</label><input type="text" id="txt1" value=""/>
</div>
jquery
$("#select1").change(function(){
if($(event.target).val() == 'A'){
$('#d1').show();
}else{
$('#d1').hide();
}
});
js
function total(){
var a = $("#input1").val();
var b = $("#input2").val();
var c = $("#input3").val();
var d = parseFloat(a, 10);
var e = parseFloat(a, 10);
var f = parseFloat(a, 10);
total = d + e + f;
$('#txt1').val(total.toFixed(2));$(
}
Try
jQuery(function($) {
$("#select1").change(function() {
$('#d1').toggle($(this).val() == 'A');
});
$('#input1, #input2, #input3').change(total)
function total() {
var a = $("#input1").val();
var b = $("#input2").val();
var c = $("#input3").val();
var d = parseFloat(a, 10) || 0;
var e = parseFloat(b, 10) || 0;
var f = parseFloat(c, 10) || 0;
total = d + e + f;
$('#txt1').val(total.toFixed(2));
}
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<select id="select1">
<option value="A">New</option>
<option value="B">Satisfied</option>
</select>
<div id="d1">
<label>This is a default value</label>
<input type="text" id="input1" placeholder="$75,000" style="width: 100px;" />
<label>Preferred Value:</label>
<input type="text" id="input2" value="" style="width: 100px;" />
<label>Number of Contributors:</label>
<input type="text" id="input3" value="" style="width: 100px;" />
<label>Total:</label>
<input type="text" id="txt1" value="" />
</div>
As stated, i's not clear what the question is. I'm assuming you're problem is it just doesn't work. Looking at your code it wouldn't. I re-wrote some of your stuff and I think this is what you are looking for
$("#select1").change(function(event){
if($(this).val() == 'A'){
$('#d1').show();
}else{
$('#d1').hide();
}
});
$("input").blur(function(){
total();
});
function total(){
var a,b,c = 0;
var a = $("#input1").val();
var b = $("#input2").val();
var c = $("#input3").val();
if(a != ""){
var d = parseFloat(a, 10);
}else{
var d = 0;
}
if(b != ""){
var e = parseFloat(b, 10);
}else{
var e = 0;
}
if(c != ""){
var f = parseFloat(c, 10);
}else{
var f = 0;
}
var calcTotal = d + e + f;
$('#txt1').val(calcTotal.toFixed(2));
}
You're getting NaN cause it's trying to float a number that doesn't exist. You can check to see if that field has a value and if not render 0
FIDDLE
UPDATE
That's simple enough, just reset the values when you hide the div
NEW FIDDLE
Simply copy and paste code. It is same code as yours, I have done some basic modification in Jquery and there was also mistakes in your html.......plz check it, it will work perfectly. thnx
<html>
<head>
<script src="http://code.jquery.com/jquery-1.10.2.js"></script>
<script >
$(document).ready(function() {
$("#select1").change(function(){
if($(event.target).val() == 'A'){
$('#d1').show();
}else{
$('#d1').hide();
}
});
});
</script>
<script type="text/javascript">
function total(){
var a = $("#input1").val();
var b = $("#input2").val();
var c = $("#input3").val();
var d = parseFloat(a, 10);
var e = parseFloat(a, 10);
var f = parseFloat(a, 10);
total = d + e + f;
document.getElementById('txt1').value=total;
}
</script>
</head>
<body>
<select id="select1">
<option value="A">New</option>
<option value="B">Satisfied</option>
</select>
<div id="d1">
<label>This is a default value</label><input type="text" id="input1" placeholder="$75,000" style="width: 100px;"/>
<label>Preferred Value:</label><input type="text" id="input2" value="" style="width: 100px;"/>
<label>Number of Contributors:</label><input type="text" id="input3" value="" style="width: 100px;"/>
<label>Total:</label><input type="text" id="txt1" value="" onclick="total();" />
</div>
</body>
</html>
try this: And please do change your html also they have some error like in select for B you have not closed ".
$("#select1").change(function(event){
if($(event.target).val() == 'A'){
$('#d1').show();
}else{
$('#d1').hide();
$('#txt1').val(0);
}
});
$("input").on('blur',function(){
total();
});
function total(){
var a = $("#input1").val();
var b = $("#input2").val();
var c = $("#input3").val();
var total=0;
if(a.length > 0){
var d = parseFloat(a, 10);
total=total+d;
}
if(b.length > 0){
var e = parseFloat(b, 10);
total=total+e;
}
if(c.length > 0){
var f = parseFloat(c, 10);
total=total+f;
}
$('#txt1').val(total.toFixed(2));
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="select1">
<option value="A">New</option>
<option value="B">Satisfied</option>
</select>
<div id="d1">
<label>This is a default value</label><input type="text" id="input1" placeholder="$75,000" style="width: 100px;" >
<label>Preferred Value:</label><input type="text" id="input2" value="" style="width: 100px;" />
<label>Number of Contributors:</label><input type="text" id="input3" value="" style="width: 100px;" />
<label>Total:</label><input type="text" id="txt1" value=""/>
</div>