Reset total sum if input changes with jquery change event - javascript

I have a list of inputs that i'll be using to set values (0 to 100).
The total values from those inputs can't be more than 100, i have this done and it's working, but i need a way to subtract the total if i change one of those inputs and the total becomes < 100
Here's one example for what i have so far:
var soma_total = 0;
jQuery(function($){
$('input[type=text]').each(function () {
$(this).change(function(){
var valor = $(this).val();
valorPorcentagem = valor;
eE = procPorcentagem(valorPorcentagem);
eE = Math.ceil(eE);
valorPorcentagem = parseInt(valorPorcentagem);
if((parseInt(valorPorcentagem) + soma_total) > 100)
valorPorcentagem = 100 - soma_total;
$(this).val(valorPorcentagem);
soma_total += valorPorcentagem;
console.log(soma_total);
$('#final_sum').append('<li>'+soma_total+'</li>');
});
});
});
function procPorcentagem(entradaUsuario){
var resultadoPorcem = (entradaUsuario * 48) / 100;
return resultadoPorcem;
}
JSFiddle
Help please, thanks!

This demo might give you an idea on how to proceed:
$(function() {
$(':text').val(0).on('change', function(e) {
var i = $(':text'),
total = 0;
i.each(function() {
total += +this.value;
});
if( total > 100 ) {
this.value -= (total - 100);
}
total = 0;
i.each(function() {
total += +this.value;
});
$('#final_sum').text( total );
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="text">
<input type="text">
<input type="text">
<div id="final_sum">0</div>

Related

Removing the shipping price, if the amount has reached a certain value

So I have a working shopping cart page, but I do not know how to remove the shipping value, once a user has reached a total, for example, of 50 or higher. In the previous version this was already implemented, so I tried to compare and figure out how to implement this in the new page, but am not skilled enough in JavaScript. This is the JavaScript I am using right now.
$(document).ready(function() {
var taxRate = 0.05;
var shippingRate = 5.00;
var fadeTime = 300;
$('.product-quantity input').change( function() {
updateQuantity(this);
});
$('.product-removal button').click( function() {
removeItem(this);
});
function recalculateCart()
{
var subtotal = 0;
$('.product').each(function () {
subtotal += parseFloat($(this).children('.product-line-price').text());
});
var tax = subtotal * taxRate;
var shipping = (subtotal > 0 ? shippingRate : 0);
var total = subtotal + tax + shipping;
$('.totals-value').fadeOut(fadeTime, function() {
$('#cart-subtotal').html(subtotal.toFixed(2));
$('#cart-tax').html(tax.toFixed(2));
$('#cart-shipping').html(shipping.toFixed(2));
$('#cart-total').html(total.toFixed(2));
if(total == 0){
$('.checkout').fadeOut(fadeTime);
}else{
$('.checkout').fadeIn(fadeTime);
}
$('.totals-value').fadeIn(fadeTime);
});
}
function updateQuantity(quantityInput)
{
var productRow = $(quantityInput).parent().parent();
var price = parseFloat(productRow.children('.product-price').text());
var quantity = $(quantityInput).val();
var linePrice = price * quantity;
productRow.children('.product-line-price').each(function () {
$(this).fadeOut(fadeTime, function() {
$(this).text(linePrice.toFixed(2));
recalculateCart();
$(this).fadeIn(fadeTime);
});
});
}
function removeItem(removeButton)
{
var productRow = $(removeButton).parent().parent();
productRow.slideUp(fadeTime, function() {
productRow.remove();
recalculateCart();
});
}
});
Set shipping to zero when subtotal + tax >= 50 (assuming that's the business rule).
var shipping = subtotal > 0 && (subtotal + tax < 50) ? shippingRate : 0;
And then, for display purposes, set the shipping value element to empty when shipping === 0. A ternary operator is one way to do it.
$('#cart-shipping').html(shipping === 0 ? '' : shipping.toFixed(2));

Show an error when sum value is over 100

I'm trying to sum 100 on a variable ammount of input fields. I'm doing this using this Javascript:
$('.price').keyup(function () {
var sum = 0;
$('.price').each(function() {
sum += Number($(this).val());
});
$('#totalPrice').val(sum);
});
And it works! but now i need to do two things; if the user inputs a value different than a number, or if the total value is over 100, show a hidden div.
I'm really new Javascript, and i made this code but showing an error are major words for me now.
Thank you guys!
you might want something like this:
$('.price').keyup(function() {
var sum = 0;
$('.price').each(function() {
var inputVal = +$(this).val(); //each field's value converted to number using "+"
if (!isNaN(inputVal)) {
sum += inputVal;
$('.not-num-err').hide();
} else {
$('.not-num-err').show();
return false; //stop iteration
}
});
if (sum > 100) {
$('.over-hundred-err').show();
} else {
$('.over-hundred-err').hide();
}
$('#totalPrice').val(sum);
});
.hidden {
display: none
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" class="price">
<input type="text" class="price">
<input type="text" class="price">
<div class="not-num-err hidden">You entered wrong number</div>
<div class="over-hundred-err hidden">Total is over 100!</div>
<p>
<label for="totalPrice">Total Price</label>
<input type="text" id="totalPrice">
check this link for more info on the unary plus (+) operator.
You can use this keyword inside it:
$('.price').keyup(function() {
if (isNaN(this.value) || (!isNaN(this.value) && this.value > 100)) {
// Do something.
alert("No!");
// Do not allow the function to proceed.
return false;
}
var sum = 0;
$('.price').each(function() {
sum += Number($(this).val());
});
$('#totalPrice').val(sum);
});
Working Fiddle: https://jsfiddle.net/ash06229/ydbjsx1z/
Try this:
$('.price').keyup(function () {
var sum = 0;
$('.price').each(function() {
if(sum <= 100)
{
$('.error').html("");
sum += Number($(this).val());
}
else {
$('.error').html("Sum is greater than 100").css("color","red");
}
});
$('#totalPrice').val(sum);
});

Javascript total return NaN for 4 digits num

Here is the javascript for calculating the price of the item the problem is that
whenever the price is 4 digits the value that return is NaN.
here's my hidden field for the price:
<input type="hidden" name="price" id="price"class="price" value="4500"readonly >
here's for my quantity field
<input type="number" name="quant" id="quant" value="2" />
here's for my shipment fee
<select id="shipment" onchange="myFunction3()" name="shipment2" disabled>
<option value="100" data-quantity="1">1 for 100 pesos </option>
</select
here's for the total price
<input type="text" id="demo" name="total_price" style="margin-top:10px;margin-left:5px;" readonly>
Script for changing the value of shipment
<script type="text/javascript">
document.getElementById('quant').addEventListener("keyup", function(){
var value = parseInt(this.value, 20),
selectEle = document.getElementsByTagName('select')[0],
options = selectEle.options,
selectedNum = 0;
for(var i = 0; i < options.length; i++) {
//checking the exact string with spaces (" " + value + " ")
if(options[i].textContent.indexOf(" " + value + " ") > -1) {
selectedNum = i;
}
}
selectEle.selectedIndex = selectedNum ? selectedNum : 0;
}, false);
</script>
Calculating all the values
function myFunction3() {
var y= document.getElementById("shipment").value;
return y;
}
<script>
$("#price,#quant,#shipment").keyup(function () {
if(+myFunction3() =="" )
{
$('#demo').val(0);
}
else if($('#trigger')=="checked") //this is the problem
{
$('#demo').val($('#price').val() * $('#quant').val() ;
}
else
{
$('#demo').val($('#price').val() * $('#quant').val() + +myFunction3());
}
});
</script>
Not sure if this was just typed incorrectly in here, but you have a syntax error (missing closing parenthesis) near the problem area:
$('#demo').val($('#price').val() * $('#quant').val() ;
Should be:
$('#demo').val($('#price').val() * $('#quant').val());
I think it would be much better to ensure you aren't working with strings before you do math on them:
var price = parseInt($('#price').val(), 10);
var quantity = parseInt($('#quant').val(), 10);
$('#demo').val(price * quantity);
You could go further and ensure that neither of them are NaN prior to working with them:
var price = parseInt($('#price').val(), 10);
var quantity = parseInt($('#quant').val(), 10);
if(!isNaN(price) && !isNaN(quantity)) {
$('#demo').val(price * quantity);
} else {
alert('Please enter numbers only!');
}

Get total amount per mode using Javascript

<?php
$ctr = 0;
while($ctr <= 10){
?>
<td><input required type='text' name='amount[<?echo $ctr; ?>]' class='amount'></td>
<td><input required type='text' name='mode[<?echo $ctr; ?>]' value='Cash'></td>
<?php
$ctr++;
}
?>
Total Amount: <span class="total_amount">0.00</span>
Total Cash : <span class="total_cash">0.00</span>
Total Check: <span class="total_check">0.00</span>
$(document).on('blur','.amount',function () {
var total = 0;
var total_cash = 0;
var total_check = 0;
$('.amount').each(function () {
total += parseFloat($(this).val());
});
$('.total_amount').html(total);
});
Using the code above, I can get the total amount of the number I encode in the input amount fields. How can I get the total per mode, cash(default) and check (user can change mode to check)?
If you sure, that next input width mode always corresponds, you can use JQuery.next. So it is necessary to check the value of each parameter to NaN.
$(document).on('blur','.amount',function () {
var total = 0;
var total_cash = 0;
var total_check = 0;
var val, mode;
$('.amount').each(function () {
val = parseFloat($(this).val());
val = val ? val : 0;
total += val;
mode = $(this).next().val();
switch(mode) {
case "Check" : total_check += val; break;
case "Cash" : total_cash += val; break;
}
});
$('.total_amount').html(total);
$('.total_cash').html(total_cash);
$('.total_check').html(total_check);
});
http://jsfiddle.net/ag0a78jd/
The following only works if your indexes are consistent (eg. every amount[x] has a mode[x]):
var total = {};
$('.amount').each(function(idx)
{
var mode = $('[name="mode['+idx+']"');
if (!total[mode.val()])
total[mode.val()] = 0;
total[mode.val()] += parseFloat($(this).val());
}
);
console.log(total);
jsFiddle
Use jquery to get the index of the current element in the set of "amount" elements.
var index = $( ".amount" ).index( this );
Get the corresponding Cash/Check element value with the index you got just above
var mode_value = $("input[name='mode["+index+"]']").val();
Then check that value and store the value in the right variable
if (mode_value == "Cash")
total_cash = total_cash + $(this).val();
if (mode_value == "Check")
total_check = total_check + $(this).val();
The whole code must be inside the blur event.

JQuery Column Calculations

I need some assistance with this code:
http://jsfiddle.net/N5xTJ/1/
The last column already is dynamic through jQuery, which calculates "Packs QTY" x "Price", then totals on the bottom.
I need help doing the calculation for total QTY based on <TD CLASS="QTY"> and it will show results in totalsqty.
Also for TotalUnits Needs to calculate "Qty" X "Units Per Pack" and show in "Total Units".
JS that is currently doing the totals for #Total Price:
function ca(){
var $overall = 0;
$("tr.sum").each(function() {
var $row=$(this);
var $qnt = $(this).find(".qty");
var cost = $row.data('unit_price');
var sum = cost * parseFloat($qnt.val());
$(this).find("td").eq(5).text('$' +sum);
$overall += sum;
});
$("#total").text('$' +$overall);
}
$(function() {
ca();
$('input.qty').bind('change keyup', ca);
});
Try this fiddle: http://jsfiddle.net/N5xTJ/4/
I've updated your existing code, to accommodate totalUnits and totalQty.
Code (with comments):
function ca() {
var $overall = 0,
totalQty = 0,
totalUnits = 0;
$("tr.sum").each(function() {
var $row = $(this),
qnt = parseInt($(this).find("input.qty").val()),
cost = $row.data('unit_price'),
sum = cost * qnt,
upp = parseInt($row.find('.upp').text());
$row.find('span.t-units').text(upp * qnt);
$(this).find("td").eq(5).text('$' + sum);
totalQty += qnt;
totalUnits += parseInt($row.find('span.t-units').text());
$overall += sum;
});
$("#total").text('$' + $overall);
$('#totalqty').text(totalQty);
$('#totalunits').text(totalUnits);
}
$(function() {
ca();
$('input.qty').bind('change keyup', ca);
});​
I've also cleaned up the code a bit, so have a look and let me know if you have questions.

Categories

Resources