Check if the sum of fields are greater than 100? - javascript

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" />

Related

How to know if one of the checkboxes is selected with Javascript

I have many checkboxes with prices. I want that every time the user selects a checkbox, the final price is updated. I have done it with JQuery but the function is never entered.
$('input[type=checkbox]:checked').on('change', function() {
console.log("Hi")
var total = 0;
var result = document.getElementById('result');
if ($('checkbox1').prop("checked")) {
total += 100;
}
if ($('checkbox2').prop("checked")) {
total += 50;
}
if ($('checkbox3').prop("checked")) {
total += 250;
}
result.innerText = 'Result: ' + total + '€';
});
HTML:
<input type="checkbox" name="myCheckbox" id="checkbox1" value="yes"/> 7:30h-21:00h - 250€
<div id="result"><p>Result: </p></div>
I would also like to know if there is something like:
$('input[type=checkbox]:checked').on('change', function() || $('#num').on("keyup", function() {
Because I want it to enter the function whether a checkbox has been selected or if it has selected a number in the input:number.
I think .on() function in jQuery's newer version is obsolete now try this way.
$('input[type="checkbox"]').change(function () {
console.log("Hi")
var total = 0;
var result = document.getElementById('result');
if ($('checkbox1').prop("checked")) {
total += 100;
}
if ($('checkbox2').prop("checked")) {
total += 50;
}
if ($('checkbox3').prop("checked")) {
total += 250;
}
result.innerText = 'Result: ' + total + '€';
});

Get value of variable inside .each() function jQuery

I have code below.
The code works fine, but if I uncomment the "if" statement, alert will show up as soon as I enter something to input field.
I want the "sum" value to be checked (alert shows up) only after I entered all 3 input fields.
Please help me to fix it. Thanks.
<apex:inputField styleClass="Weight" value="{!EvaluationInformation__c.val1__c}" />
<apex:inputField styleClass="Weight" value="{!EvaluationInformation__c.val2__c}" />
<apex:inputField styleClass="Weight" value="{!EvaluationInformation__c.val3__c}" />
$(document).ready(function() {
$(document).on("input", ".Weight", function(e) {
var sum = 0;
$('.Weight').each(function() {
var num = $(this).val();
if (num != null && !isNaN(num)) {
sum += parseFloat(num);
} else {
alert("Accept number only");
}
});
//if (sum != 1){ // sum !=1 doesn't work
// alert("The total of Weight must be 1");
//}
});
});
You can use a status flag that will tell if all inputs are valid, see my example code below.
Also, AFAIK val() for an <input> element never returns null, it returns "" if there is no input. This is why I used if (num && ... instead, which in this situation means "only proceed if num contains text".
$(document).ready(function() {
$(document).on("change", ".Weight", function(e) {
var sum = 0;
var allInputsValid = true; // <-- flag variable
$('.Weight').each(function() {
var num = $(this).val();
if (num && !isNaN(num)) {
sum += parseFloat(num);
} else {
allInputsValid = false;
}
});
if (allInputsValid) {
console.log("All inputs have numbers.");
if (sum != 1) {
console.log("The total of Weight must be 1, but it is: " + sum);
} else {
console.log("The total of Weight is 1.");
}
} else {
console.log("Not all input have numbers yet.");
}
});
});
.Weight { width: 50px }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
#1: <input class="Weight" /> #2: <input class="Weight" /> #3: <input class="Weight" />
PS - Even then, you may have trouble making this work because of how Floating Point math works. Due to internal rounding, a sum of numbers that you would expect to be 1 will not always produce exactly 1:
var x = parseFloat("0.34") + parseFloat("0.56") + parseFloat("0.10");
console.log(x);
console.log(x === 1);

Change range element's step depending on it's value

Right now I have this range element:
<input type="range"
onchange= "calculate();"
id="sumRange"
min="50000"
max="500000"
value="50000"
step= "50000"/>
I want its "step" to change depending on its value. For example, if the value is less than 200000 then step = 5000, if more than 200000 then step= 50000.
How can I do that? Do I create a function with simple "if" statements and make it run onchange of the range?
All example i've seen involve jQuery or something else, can i do this without...that?
See below, change the ranges as needed
function calculate() {
var input = document.getElementById('sumRange');
var val = input.value;
var newStep;
if (val < 100000) {
newStep = 10;
} else if (val < 150000) {
newStep = 20;
} else if (val < 200000) {
newStep = 30;
} else if (val < 250000) {
newStep = 40;
} else {
newStep = 50;
}
input.step = newStep;
}
<input type="range"
onchange= "calculate();"
id="sumRange"
min="50000"
max="500000"
value="50000"
step= "50000"/>
here is what you can do in your calculate function, using jquery
calculate = function() {
if ($('#sumRange').attr('value') < 200000 ) {
$('#sumRange').attr('step',5000);
} else {
$('#sumRange').attr('step',50000);
}
var sumRange = document.getElementById(“sumRange”);
sumRange.oninput = function(){
var value = this.value;
if (value > 20000) {
this.step = 50000;
} else {
this.step=5000;
}

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

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