Show an error when sum value is over 100 - javascript

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);
});

Related

Adding the result of separate results

Thanks in advance for any replies. I am new to JavaScript and have got this far in calculating 2 results that I require. My question is how do I add both results together?
Please see first result below:
$(document).ready(function() {
function checkSum(e) {
var result = 0;
$(".checksum").each(function() {
var i = 0;
if ($(this).val() != "") {
i = parseFloat($(this).val());
}
result = result + i;
});
$("#resultsum").html(result * 60.60);
}
checkSum();
$(".checksum").bind("keyup", checkSum);
});
and this is the second:
$(document).ready(function() {
function checkSum2(e) {
var result2 = 0;
$(".checksum2").each(function() {
var j = 0;
if ($(this).val() != "") {
j = parseFloat($(this).val());
}
result2 = result2 + j;
});
$("#resultsum2").html(result2 * 14.88);
}
checkSum2();
$(".checksum2").bind("keyup", checkSum2);
});
Just add one line in the end of functions:
$("#resultsum3").html($("#resultsum").text() + $("#resultsum2").text());
$(document).ready(function() {
function checkSum(e) {
var result = 0;
$(".checksum").each(function() {
var i = 0;
if ($(this).val() != "") {
i = parseFloat($(this).val());
}
result = result + i;
});
$("#resultsum").html(result * 60.60);
$("#resultsum3").html($("#resultsum").text() + $("#resultsum2").text());
}
checkSum();
$(".checksum").bind("keyup", checkSum);
function checkSum2(e) {
var result2 = 0;
$(".checksum2").each(function() {
var j = 0;
if ($(this).val() != "") {
j = parseFloat($(this).val());
}
result2 = result2 + j;
});
$("#resultsum2").html(result2 * 14.88);
$("#resultsum3").html($("#resultsum").text() + $("#resultsum2").text());
}
checkSum2();
$(".checksum2").bind("keyup", checkSum2);
});
I've combined your snippets in to one to remove the redundant code you have. This approach will allow you to add more checksums in future (.checksum3?) and also makes sure your calculation logic is same for all.
The result is calculated in to new element whenever any of the checksums change. Try the snippet below:
// function to calculate checksum
// used for both individual results as well as for total
function calcChecksum(elements) {
let result = 0;
elements.each( function(index, ele) {
result = result + (parseFloat($(ele).val()) || 0)
});
return result;
}
// update total result
function updateTotal() {
let total = calcChecksum($('.result'));
$('#resultsum_total').val(total);
}
$(document).ready(function() {
// generate function for each set of checksum inputs
function genCheckSumFn(inputSel, outputSel, multiplier) {
return () => {
const result = calcChecksum($(inputSel));
$(outputSel).val(result * multiplier);
updateTotal();
}
}
//checkSum bindings
$(".checksum").bind("keyup",
genCheckSumFn('.checksum','#resultsum',60.60)
);
$(".checksum2").bind("keyup",
genCheckSumFn('.checksum2','#resultsum2',14.88)
);
// trigger initial calculation
$(".checksum").trigger('keyup');
$(".checksum2").trigger('keyup');
});
.checksum,
.checksum2{
display: block;
}
.box {
padding:10px 0px;
}
.box div {
margin-top:5px;
}
.box.results input {
color: #FFA500;
border:0px;
font-size: 14px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="box">
Checksum
<input class="checksum" value="10">
<input class="checksum" value="5">
Checksum(2)
<input class="checksum2" value="20">
<input class="checksum2" value="15">
<div>
<div class="box results">
<div> Resultsum:
<input id="resultsum" class="result" readonly> </div>
<div> Resultsum(2):
<input id="resultsum2" class="result" readonly> </div>
<div> Resultsum(Total): <input id="resultsum_total" readonly> </div>
</div>

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!');
}

Sum Checkboxes without POSTING values - Javascript

I've had a look around but could find a definitve answer.
Basically, I have a Total, with an ID that im trying to automatically update once a checkbox is clicked.
p style="font-size: 1.2em; font-weight: bold;"><b>Total Cost:</b> £<input value="0.00" readonly="readonly" type="text" id="total"/></p>
The checkbox will have a simple value such as 1.50 or similar. (these are dynamic) so
<input name="product" value="<?php echo $count*0.50 ?>" type="checkbox">
This may be very simple! But im not that hands on with Javascript
Handling both checking and unchecking a box to update the sum for the input with a working jsbin example, also assuming you are using jquery.
var sum = 0;
var total = $('#total');
var cbox = $('.cbox');
$('.cbox').on('change', function() {
if ($(this).prop('checked')) {
sum += parseFloat($(this).val());
updateTotal();
} else {
sum -= parseFloat($(this).val());
updateTotal();
}
});
function updateTotal() {
total.val(sum);
}
$('input[type=checkbox]').change(function() {
var sum = 0;
$('input[type=checkbox]:checked').each(function() {
sum += Number($(this).val());
});
$('#total').val(sum);
});
IF you just want the checked "product" check boxes:
$('input[type="checkbox"][name="product"]').on('change', function() {
var newtotal = 0;
$('input[type="checkbox"][name="product"]').filter(":checked").each(function() {
newtotal = newtotal + Number($(this).val());
});
$('#total').val(newtotal);
});
Sample fiddle to play around with: https://jsfiddle.net/ovqkcqvn/

Reset total sum if input changes with jquery change event

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>

jQuery result not displaying in field

For some reason I just can't get this result to display in the field using an id. It worked fine using a class but it just refuses to work using an id.
JSFiddle here http://jsfiddle.net/pbe4b/15/
Works fine:
<input id="button123" placeholder="number here"></input>
<span class="output123"></span>
Doesn't work:
<input id="button123" placeholder="number here"></input>
<input id="output123"></input>
Would love any help!
use
$('#output123').val()
instead of
$('#output123').html()
input is self closing tag so you should use val() to get value from this .
You have changed spans to inputs, and so .html() is no longer valid. The selector is fine. Change all instances of .html() to .val().
HTML:
<input id="button123" placeholder="number here"></input>
<input id="output123"></input>
JavaScript:
$('#button123').keyup(function(){
var n = parseInt($(this).val());
if(n <= 35000) {
$('#output123').val(numberWithCommas((n/100*70).toFixed(2)));
}
else if(n <= 45000) {
$('#output123').val(numberWithCommas((n/100*75).toFixed(2)));
}
else {
$('#output123').val(numberWithCommas((n/100*80).toFixed(2)));
}
})
function numberWithCommas(x) {
return x.toString().replace(/\B(?=(?:\d{3})+(?!\d))/g, ",");
}
JSFiddle Here.
http://jsfiddle.net/pbe4b/19/
Vals instead of HTML since it is an input
$('#button123').keyup(function(){
var n = parseInt($(this).val());
if(n <= 35000) {
$('#output123').val(numberWithCommas((n/100*70).toFixed(2)));
}
else if(n <= 45000) {
$('#output123').val(numberWithCommas((n/100*75).toFixed(2)));
}
else {
$('#output123').val(numberWithCommas((n/100*80).toFixed(2)));
}
})
function numberWithCommas(x) {
return x.toString().replace(/\B(?=(?:\d{3})+(?!\d))/g, ",");
}
$('#button123').keyup(function(){
var n = parseInt($(this).val());
if(n <= 35000) {
$('#output123').val(numberWithCommas((n/100*70).toFixed(2)));
}
else if(n <= 45000) {
$('#output123').val(numberWithCommas((n/100*75).toFixed(2)));
}
else {
$('#output123').val(numberWithCommas((n/100*80).toFixed(2)));
}
})
function numberWithCommas(x) {
return x.toString().replace(/\B(?=(?:\d{3})+(?!\d))/g, ",");
}`enter code here`
Use $('#output123').val() to set the value.
It has nothing to do with a class/id, it is due to the fact you changed the element.
inputs do not have html(), you use val() to set the value.
Cleaned up code without all the copy and paste:
$('#button123').keyup(function(){
var n = parseInt($(this).val(), 10);
var calc;
if(n <= 35000) {
calc = n/100*70;
} else if(n <= 45000) {
calc = n/100*75;
} else {
calc = n/100*80;
}
var val = numberWithCommas(calc.toFixed(2));
$('#output123').val(val);
});
To set the value of a input use:
JS:
document.getElementById('output123').value = 'my value';
jQuery:
$('#output123').val('my value');
.html is used to replace the inner content of an item, in the case of input you need to change an attribute.

Categories

Resources