on click remove field,amount get reduced but it shows -ve sign - javascript

Function to remove fields and substract amount from total:
function removeHtmlRow(nxt){
$("#FD"+nxt).remove();
var totAmtR = 0;
$('input.price').each(function (index, cvalue) {
if(cvalue.value != '' && cvalue.value > 0){
totAmtR -= parseFloat(cvalue.value);
}
});
alert(totAmtR);
$("#totalAmount").val(parseFloat(totAmtR));
}
Function to calculate total:
function calTotalAmount(){
var totAmt = 0;
$('input.price').each(function (index, cvalue) {
if(cvalue.value != '' && cvalue.value > 0){
totAmt += parseFloat(cvalue.value);
}
});
$("#totalAmount").val(parseFloat(totAmt));
}
</script>
screenshot shows: after remove field total show remaining amount with -ve

In your removeHtmlRow function you are subtracting everything from 0, so it will be negative. Just recalculate the amount using your existing calTotalAmount function:
function removeHtmlRow(nxt){
$("#FD"+nxt).remove();
calTotalAmount()

Related

Javascript: how to calculate the total [duplicate]

This question already has answers here:
Variable keeps getting reset to its original value
(2 answers)
Closed 4 years ago.
I have a problem with the total price of a cart. Theoretically, the function should update the total whenever I press the "buy" button, but it just replaces the price.
Instead of doing 0 + price + price + price +..., it does 0 + price, then again 0 + price.
How can I fix it?
function buy(id) {
var total = 0;
for (var i in albums) {
if (albums[i].id == id) {
if (albums[i].quantity > 0) {
albums[i].quantity--;
total += albums[i].price;
}
}
}
for (var i in singles) {
if (singles[i].id == id) {
if (singles[i].quantity > 0) {
singles[i].quantity--;
total += singles[i].price;
}
}
}
for (var i in soundtracks) {
if (soundtracks[i].id == id) {
if (soundtracks[i].quantity > 0) {
soundtracks[i].quantity--;
total += soundtracks[i].price;
}
}
}
document.getElementById('purchases').innerHTML = total;
}
<button onClick='buy("+this.id+")'>Buy</button>
Everytime time you do a button click, you are calling yourbuy function. In that function you are declaring var total = 0. Thats why it always starts with 0. You should declare your total not with 0 but with previous number. In your case, that would be from document.getElementById('purchases').innerHTML. So
total = document.getElementById('purchases').innerHTML, or move var total = 0 outside of function.
I moved the total out as others pointed out, but I also made some refactors to remove repeated logic.
//moved the total outside of the method so it is not reinitialized
//as others have already mentioned
var total = 0;
//also reduced your repeated logic
function totalElements (elements, id) {
elements.forEach(function(element){
if (element.id == id && element.quantity > 0) {
element.quantity--;
total += element.price;
}
});
}
function buy(id) {
totalElements(albums, id);
totalElements(singles, id);
totalElements(soundtracks, id);
document.getElementById('purchases').innerHTML = total;
}
<button onClick='buy("+this.id+")'>Buy</button>

Check if the sum of fields are greater than 100?

What I try to achieve to give alert if the sum of first values are greater than 100 if not third value has to be calculated like this;
3th textbox= 100- 1st textbox- 2th textbox
It works well at the beginning. When I type 100 for 1st textbox then 20 for 2nd I get error then I enter 80-30 I get again alert but then third times when I enter 50-30 I again get error but actually it shouldnt give error it should write in third textbox 20
$(document).ready(function() {
// calc
jQuery("#custom-419").on("change", function() {
var vorOrt = $(this).val();
jQuery("#custom-420").on("change", function() {
var vorOrt2 = $(this).val();
var sum = 0;
sum += parseInt(vorOrt);
sum += parseInt(vorOrt2);
console.log($('#sum').val());
if (sum <= 100) {
var onWeb = 100 - vorOrt;
onWeb = onWeb - vorOrt2;
jQuery("#421").val(onWeb);
} else {
window.alert("The sum of values can not be more than 100!");
$('#custom-419').val("");
$('#custom-420').val("");
$('#custom-421').val("");
}
});
})
});
Because all the other answers contains jQuery, I though it may be helpful to provide a vanilla JavaScript solution. Keep in mind that solution is for modern browser only!
function calc() {
const counters = [...document.querySelectorAll('.counter')];
const total = document.querySelector('.total');
const sum = counters.reduce((a, b) => a += parseInt(b.value) || 0, 0);
total.value = sum;
if (sum <= 100) return;
alert("The sum of values can not be more than 100!");
counters.forEach(x => x.value = '');
total.value = '';
}
[].forEach.call(document.querySelectorAll('.counter'), x => x.addEventListener('keyup', calc));
<div>
result has to be less then or equal 100
</div>
<input class="counter" id="#custom-419" /> +
<input class="counter" id="#custom-420" /> =
<input class="total" id="#custom-421" disabled />
Explanation
Because you didn't show us your current html, I made it simple. So no explanation required I guess.
What happens in that JS solution is pretty straight forward.
In the last line both input with the call counter are getting an EventListener to fire on keyup. You may keep the change event instead...
In the calc function all values of the counters get parsed to int and aggregated to sum. The rest of the code is nothing special.
As the above solution is for modern browsers only (ES6+), here are two more for older browsers:
IE11+ Support (Demo)
function calc() {
const counters = document.querySelectorAll('.counter');
const total = document.querySelector('.total');
const sum = Array.prototype.reduce.call(counters, function(a, b) {
return a += parseInt(b.value) || 0;
}, 0);
total.value = sum;
if (sum <= 100) return;
alert("The sum of values can not be more than 100!");
Array.prototype.forEach.call(counters, function(x) {
x.value = '';
});
total.value = '';
}
Array.prototype.forEach.call(document.querySelectorAll('.counter'), function(x) {
x.addEventListener('keyup', calc);
});
IE9+ Support (Demo)
I made two more function for this example to make it a bit more readable.
function calc() {
var counters = document.querySelectorAll('.counter');
var total = document.querySelector('.total');
var sum = getSum(counters);
total.value = sum;
if (sum <= 100) return;
alert("The sum of values can not be more than 100!");
clearCounters(counters);
total.value = '';
}
function getSum(counters) {
var result = 0;
for(var i = 0; i < counters.length; i++) {
result += parseInt(counters[i].value) || 0;
}
return result;
}
function clearCounters(counters) {
for(var i = 0; i < counters.length; i++) {
counters[i].value = '';
}
}
var _counters = document.querySelectorAll('.counter');
for(var i = 0; i < _counters.length; i++) {
_counters[i].addEventListener('keyup', calc);
}
Why nesting the 2 event functions ?
Try this :
var vorOrt = 0;
var vorOrt2 = 0;
$(document).ready(function() {
$('#custom-419').on('change', function() {
vorOrt = $(this).val();
checkInputs();
});
$('#custom-420').on('change', function() {
vorOrt2 = $(this).val();
checkInputs();
});
});
function checkInputs() {
var sum = 0;
sum += parseInt(vorOrt, 10);
sum += parseInt(vorOrt2, 10);
if (sum <= 100) {
var onWeb = 100 - vorOrt - vorOrt2;
$("#custom-421").val(onWeb);
} else {
window.alert('The sum of values can not be more than 100!');
$('#custom-419').val('');
$('#custom-420').val('');
$('#custom-421').val('');
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input class="counter" id="custom-419" type="number" />
<input class="counter" id="custom-420" type="number" />
<input class="total" id="custom-421" type="number" />
Once change function is inside the other, which is not necessary, Also reset the value of sum when alert is thrown
$(document).ready(function() {
var sum = 0; // initializing sum
function calSum(val) {
sum += val; // will add the values
console.log(sum)
if (sum <= 100) {
var onWeb = 100 - sum;
$("#custom-421").val(onWeb);
} else {
alert("The sum of values can not be more than 100!");
$('#custom-419').val("");
$('#custom-420').val("");
$('#custom-421').val("");
sum = 0;
}
}
$("#custom-419").on("change", function() {
calSum(parseInt($(this).val(), 10));
});
$("#custom-420").on("change", function() {
calSum(parseInt($(this).val(), 10));
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="custom-419">
<input type="text" id="custom-420">
<input type="text" id="custom-421">
Look at the following solution. It uses jQuery's each.
What I did is attach the same function to every input by using a descriptive class name: counter. We can easily get all the input using the selector input.counter and add an onchange event with only one line of code.
After that the generic function testIfMoreThanHundred will iterate over all the element using each and sum the values into a variable.
after that it's just a simple if check to see if the value if more than a hundred.
$(document).ready(function() {
// calc
$("input.counter").on("change", testIfMoreThanHundred);
});
//let's make a generic function shall we:
function testIfMoreThanHundred() {
var sum = 0;
//get the elements and use each to iterate over them
$("input.counter").each(function() {
var number = parseInt($(this).val(), 10);
//test if value is a number, if not use 0
if (!isNaN(number)) {
sum += parseInt($(this).val(), 10);
} else {
sum += 0;
}
});
if (sum > 100)
{
alert("The sum can't be greater than a 100");
$("input.counter").val(""); //empty the values
$("input.total").val("");
}
else
{
$("input.total").val(100 - sum); //show value in third box
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input class="counter" id="custom-419" type="number" />
<input class="counter" id="custom-420" type="number" />
<input class="total" id="custom-421" type="number" />

Value condition not working as expected

I have number of inputs and I want to set a minimum value of each input section. For example, I have set a minimum input value of 100. So if the value of any input is less than 100 from all the inputs it will show an error. Otherwise if value of all the inputs is greater than or equal to 100 it will show the success message.
In my case if I enter less than value in an input it will show error but with this less value if I enter greater value in other input it show success message.
<div class="color-quantity not-selected-inputs selected-input-wrap">
<input type="text" class="custom_small" name="custom_small" onkeydown="return myFunction(event);">
</div>
<div class="color-quantity not-selected-inputs selected-input-wrap">
<input type="text" class="custom_medium" name="custom_medium" onkeydown="return myFunction(event);">
</div>
<input type="text" class="custom_large" name="custom_large" onkeydown="return myFunction(event);">
</div>
jQuery('.selected-input-wrap > input').map(function () {
var total = 0;
jQuery('input', this).each(function () {
total += this.value * 1;
});
if (parseInt(total) <= 99) {
jQuery(".select-quantity").html('<p>Please select at least 100 for each color</p>');
} else if (parseInt(total) >= 100) {
jQuery(".select-quantity").html('<p>Success</p>');
}
Please have a look at the code and help me find out the issue
There's a couple of issues.
You should declare total outside the loop otherwise you reset it back to 0 on each iteration.
You should also use a single each() call to loop over a set of elements, as map() is intended to be used to create an array from those elements.
You only need to call parseInt() once when you add the value to total
Your else if condition is redundant and can be replaced by just else, or even a ternary as below.
Try this:
jQuery(function($) {
var total = 0;
$('.selected-input-wrap > input').each(function () {
total += parseInt(this.value, 10);
});
var msg = total >= 100 ? '<p>Success</p>' : '<p>Please select at least 100 for each color</p>';
$(".select-quantity").html(msg);
});
The total variable is looping through all the inputs and only once its returning according to your code. Try closing the each loop after the if-else condition and check once.
jQuery('.selected-input-wrap > input').map(function () {
var total = 0;
jQuery('input', this).each(function () {
total += this.value * 1;
if (parseInt(total) <= 99) {
jQuery(".select-quantity").html('<p>Please select at least 100 for each color</p>');
} else if (parseInt(total) >= 100) {
jQuery(".select-quantity").html('<p>Success</p>');
}
});
})
You can use the following jquery code :-
jQuery('.selected-input-wrap > input').map(function () {
var total = 0;
jQuery('input').each(function () {
total = $(this).val();
if (parseInt(total) <= 99) {
jQuery(".select-quantity").html('<p>Please select at least 100 for each color</p>');
}
else if (parseInt(total) >= 100) {
jQuery(".select-quantity").html('<p>Success</p>');
}
});
});
It may help you.
Try this.
var MIN = 100, value = 0;
jQuery('.selected-input-wrap > input').each(function (idx,el) {
value += parseInt(el.value);
});
if (value < MIN) {
jQuery(".select-quantity").html('<p>Please select at least 100 for each color</p>');
} else {
jQuery(".select-quantity").html('<p>Success</p>');
}
In My Case i have solved the issue as follows:
var total = 0;
var array_total = new Array();
jQuery('.selected-input-wrap > input').each(function(index, value) {
jQuery( ".right-minimu").remove();
var total = jQuery(this).val();
console.log("Total Value : " + total);
if (total != '') {
var t_array = array_total.push(total);
}
console.log('Total Array : ' + array_total);
});
/******** make array unique *************/
var unique_total = [];
jQuery.each(array_total, function(i, el) {
if (jQuery.inArray(el, unique_total) === -1)
unique_total.push(el);
});
var current_urls = jQuery(location).attr('href');
var rest = current_urls.substr(37, 9); //
var current_urls = jQuery(location).attr('href');
var rest_2 = current_urls.substr(37, 18);
var rest_3 = current_urls.substr(37, 15);
var rest_4 = current_urls.substr(37, 8);
jQuery.each(unique_total, function(key, total) {
for (var i = 0; i <= unique_total.length; i++) {
if(rest == "bracelets") {
if (parseInt(unique_total[i]) <= 99) {
jQuery(".select-quantity").css("display", "block");
jQuery(".select-quantity").html('<p>Please select at least 100 for each color</p>');
jQuery( "#order-overview-table table" ).css("display" , "none") ;
jQuery( "#order-overview-table").append("<p class='right-minimu'>Please select at least 100 for each color</p>") ;
jQuery('.btn-cart').removeAttr("onclick");
return false;
} else if (parseInt(unique_total[i]) >= 100) {
jQuery(".select-quantity").css("display", "none");
jQuery('.btn-cart').attr('onClick', 'productAddToCartForm.submit(this);');
jQuery(".select-quantity").html('<p>Products Added</p>').delay(4000);
}
}

.each function () for cloned inputs

Trying to create the Preview form and do not understand why each function () not working in this script. Or works but only for the last cloned row and ignore the zero values ​​in the previously cloned inputs.
$('input[id^=Mult_factor_]').each(function () {
var MultFactor = $(this).val();
var TotPoints = $('#Tot_points').val();
var exp1 = "Overload";
var exp2 = "Load is: ";
if (MultFactor < 1 || TotPoints > 100) {
$('#ExemptionLimitsText').text(exp1).show();
$('#PrwTotPointsText').hide();
} else {
$('#ExemptionLimitsText').text(exp2).show();
$('#PrwTotPointsText').text($('#Tot_points').val()).show();
}
});
JSfiddle
I need: If at least one of cloned MultiFactor value is zero show "Overload"
Based on your comment, you want to display the word "Overload" if either the "Additional" field is over 100 or if any of the multifactor fields is 0.
However, your loop continues to process if either of these conditions are met.
Do not use a loop, instead search specifically for a multifaktor value of 0.
var totalPoints = parseInt($('#Tot_points').val());
if(totalPoints > 100 || $('input[name="MultFaktor"]').filter(function(){return this.value=='0'}).length > 0) {
$('#ExemptionLimitsText').text("Overload").show();
$('#PrwTotPointsText').hide();
} else {
$('#ExemptionLimitsText').text("Load is: ").show();
$('#PrwTotPointsText').text(totalPoints).show();
}
Return false on overload
var valid = true;
var exp1 = "Overload";
var exp2 = "Load is: ";
var TotPoints = $('#Tot_points').val();
$('input[name=MultFaktor]').each(function () {
var $this = $(this);
if ($.trim($(this).val()) == '0' || TotPoints > 100) {
valid = false;
} else {
$('#ExemptionLimitsText').text(exp2).show();
$('#PrwTotPointsText').text($('#Tot_points').val()).show();
}
});
if (valid == false) {
e.preventDefault();
$('#ExemptionLimitsText').text(exp1).show();
$('#PrwTotPointsText').hide();
}

using jquery to sum the text box value in the child repeater control and show the total in the label in footer

I am trying this code for in jquery to sum the text box value in the child repeater control and show the total in the label in footer. I get null is null or not an object error.
function display(objSecName) {
var objsec = objSecName;
// var lablTotAmount = document.getElementById(objSecName);
alert(objsec);
$('.totamt input[type=text]').each(function () {
$(this).change(function () {
alert(calsum());
});
});
function calsum() {
var Total = 0;
var limtamt = 120000;
$('.totamt input[type=text]').each(function () {
if (!isNaN(this.value) && this.value.length != 0) {
Total += parseFloat($(this).val());
document.getElementById(lblTotalAmountId80C).value = Total;
}
});
return Total;
};
}
Hmm, you should try to limit your code a bit when posting here.
I cleared it up a bit for you.
Most likely the isNaN is a bit annoying in this case, I replaced that with the jquery-variant isNumeric.
function display(objSecName) {
$('.totamt input[type=text]').change(function () {
alert(calsum());
});
function calsum() {
var total = 0;
$('.totamt input[type=text]').each(function () {
var value = parseFloat(this.value);
if ($.isNumeric(value)) {
total += value;
}
});
document.getElementById(lblTotalAmountId80C).value = total;
return total;
};
}

Categories