I have a table that sum values. How can I do for when I type something that is not a number, keep the result at 0?
Some code:
$(document).on('keyup','input',newSum);
function newSum() {
var sum = 0;
var thisRow = $(this).closest('tr');
var total = 0;
$(thisRow).find("td:not(.total) input").each(function () {
sum += parseInt(this.value);
});
// Insertamos el color de la suma de cada fila.
if((sum % 2 == 0)) {$(thisRow).find('.total').animate( { backgroundColor: 'green' }, 1000);}
else{$(thisRow).find('.total').animate( { backgroundColor: 'red' }, 1000);}
$(thisRow).find(".total").html(sum);
$('.total').each(function () {
total += parseInt($(this).html());
});
}
FULL CODE
Thank you in advance.
Try short circuit boolean evaluation: sum += +this.value || 0;
The + tries to box the value to a Number, if that fails use value 0
sum+= isNaN(Number(this.value))?0:Number(this.value);
Code to stop the keypress for non numeric numbers
Code Here
Js Code :
function checkAlphbet(event) {
var code = event.keyCode ? event.keyCode : event.which;
var currentKey = alphabetKeyRestriction(code, true);
if (!currentKey) {
event.stopPropagation();
} else {
event.preventDefault();
}
}
Related
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()
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" />
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);
}
}
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;
};
}
I want to do a count down and want to show like format as Minutes:Seconds:Milliseconds. I made a count down with jquery plug-in countdown but it shows just Minutes:Seconds format.
Is there any way to make it right?
Many Thanks!
Hi guys I have developed a code for my self use the following code
counter for 20 seconds
var _STOP =0;
var value=1999;
function settimer()
{
var svalue = value.toString();
if(svalue.length == 3)
svalue = '0'+svalue;
else if(svalue.length == 2)
svalue = '00'+svalue;
else if(svalue.length == 1)
svalue = '000'+svalue;
else if(value == 0)
svalue = '0000';
document.getElementById('cn1').innerHTML = svalue[0];
document.getElementById('cn2').innerHTML = svalue[1];
document.getElementById('cn3').innerHTML = svalue[2];
document.getElementById('cn4').innerHTML = svalue[3];
value--;
if (_STOP==0 && value>=0) setTimeout("settimer();", 10);
}
setTimeout("settimer()", 10);
Try this: http://jsfiddle.net/aamir/TaHtz/76/
HTML:
<div id="timer"></div>
JS:
var el = document.getElementById('timer');
var milliSecondsTime = 10000;
var timer;
el.innerHTML = milliSecondsTime/1000;
timer = setInterval(function(){
milliSecondsTime = milliSecondsTime - 1000;
if(milliSecondsTime/1000 == 0) {
clearTimeout(timer);
el.innerHTML = 'BOOOOM';
}
else {
el.innerHTML = milliSecondsTime/1000;
}
},1000);
If you want to make your own timer.
read this earlier question
How to create a JQuery Clock / Timer
Try setting the format parameter - http://keith-wood.name/countdownRef.html#format
On further reading, this plugin doesn't do milliseconds. At this point, you either have to edit the actual plugin code or find a new plugin.
I completely agree with #Matt Ball's comment.It may also cause the browser to crash.
Why don't you try this solution instead
jQuery 1 minute countdown with milliseconds and callback
I did it like this (generic counter from N to X (X > N)):
var dynamicCounterAddNewValue = 20;
var currentDynamicUpdater;
function dynamicCounterForValueForControlUpdater(_updaterData) {
_updaterData.from += dynamicCounterAddNewValue;
if (_updaterData.from > _updaterData.to) {
_updaterData.from = _updaterData.to;
}
_updaterData.c.html(_updaterData.from.toString());
if (_updaterData.from < _updaterData.to) {
currentDynamicUpdater = setTimeout(
dynamicCounterForValueForControlUpdater,
10,
{
c: _updaterData.c,
from: _updaterData.from,
to: _updaterData.to
}
);
}
else {
clearTimeout(currentDynamicUpdater);
}
return;
}
// _c -> jQuery object (div,span)
// _from -> starting number
// _to -> ending number
function dynamicCounterForValueForControl(_c, _from, _to) {
clearTimeout(currentDynamicUpdater);
dynamicCounterForValueForControlUpdater(
{
c: _c,
from: _from,
to: _to
}
);
return;
}
EDIT: Updated version (more flexible - for N elements one after another):
(input element is Array of elements for making them dynamic-counts)
var dynamicCounterTimeout = 10;
var currentDynamicUpdater;
function odcArray(_odca) {
this.odca = _odca;
return;
}
function odc(_c, _from, _to) {
this.c = _c; // $('#control_id')
this.from = _from; // e.g. N
this.to = _to; // e.g. M => (M >= N)
var di = parseInt(_to / 45, 10);
if (di < 1) {
di = 1;
}
this.dynamicInc = di;
return;
}
function dynamicCounterForValueForControlUpdater(_odca) {
if (
_odca.odca === null
||
!_odca.odca.length
) {
clearTimeout(currentDynamicUpdater);
return;
}
var o = _odca.odca[0];
o.from += o.dynamicInc;
if (o.from > o.to) {
o.from = o.to;
_odca.odca.shift(); // Remove first element
}
o.c.html(o.from.toString());
currentDynamicUpdater = setTimeout(
dynamicCounterForValueForControlUpdater,
dynamicCounterTimeout,
_odca
);
return;
}
function dynamicCounterForValueForControl(_odca) {
clearTimeout(currentDynamicUpdater);
// SETUP all counters to default
for (var i = 0; i < _odca.odca.length; i++) {
_odca.odca[i].c.html(_odca.odca[i].from.toString());
}
dynamicCounterForValueForControlUpdater(
_odca
);
return;
}