Calculating average of a set of numbers without postback - javascript

I need to enter a set of numbers in a textbox in this form 12, 13, 54, 12 and calculate the average of the numbers from the textbox.
Is their any form or something with javascript or jquery to calculate this on realtime or without post back.
Thanks

$(document).ready(function(){
$("#yourtextbox").keyup(function(){
var text = $(this).val();
var arr = text.split(',');
var sum = 0;
var count = 0;
$.each(arr,function(index,value){
var currentItem = parseInt(value);
if (!isNaN(currentItem)){
sum+= currentItem;
count++;
}
});
console.log(sum/count);
$("#result").text(sum/count);
});
});
Demo

$('.x').keyup(function(){
var total = 0;
$('.x').each(function()
{
var value = parseInt($(this).val());
if(!isNaN(value))
total += value;
})
alert(total);})
I saved a fiddle http://jsfiddle.net/hcs49/; instead of using class selector, you could also use input[type=text]

Related

jQuery - Round Up all Currency Prices with Multiple Elements

I'm working in Shopify with it's currency switcher and the problem is, the client I'm working with wants every currency bar the default (GBP) to round it's price up to the nearest whole number, so $458.54 becomes $459.
I almost got it to work, except when more than one .money element is present, it seems to break and merges them together.
The JS code is:
var all = $(".money")
.map(function() {
return this.innerHTML;
})
.get();
var all = [all, ","];
var arrayLength = all.length;
for (var i = 0; i < arrayLength; i++) {
//Do something
}
console.log("array:", all);
var regex = all.toString().replace(/[^0-9.]/g, "");
var regex = [regex, ","];
var regexarrayLength = regex.length;
for (var i = 0; i < regexarrayLength; i++) {
//Do something
}
console.log("arrayregex:", regex);
console.log("regex:", regex);
var rounded_currency = Math.round(regex);
console.log("rounded_currency:", rounded_currency);
$("#update").click(function() {
alert(rounded_currency);
});
$(document).ready(function() {
$(".priceUpdate").text(regex);
$(".priceRound").text(rounded_currency);
});
CodePen Example
You can make use of javascript's Math.ceil() function to round up to the nearest integer.
For example, loop over the array of all selectors with the .money class and first strip the dollar sign. Then call Math.ceil().
var all = $(".money").map(function() {
return this.innerHTML;
}).get();
//["$6453.65", "$6453.65", "$453.65", "$643.65", "$6564453.65"]
var rounded = all.map(function(x) {
var numbers = x.replace(/[^0-9]/, '');
return Math.ceil(numbers);
});
//[6454, 6454, 454, 644, 6564454]
To achieve expected result, use below option
Changing array of prices to rounded prices array,as regex is not a proper array that is why it is throwing NaN
Updated codepen with JPY value for testing
console.log("array:", all);
var prices = all[0].map(function(num){
return var prices = all[0].map(function(num){
return Math.round(num.replace(/,/g, '').substr(1));
})
console.log(prices)
})
console.log(prices);//rounded prices [6454,6454,454,644,6564454]
Codepen-https://codepen.io/nagasai/pen/VbMZBz?editors=1111

amount after ',' cannot be read

i have a js code that calculate the total amount when being click by checkbox. The user can either choose to select all or select only certain amount that they want to calculate. The function if the user 'select all'is work fine but when they click only certain amount that they want to calculate, if the amount is have ','in it, it will only take the number before the ','for example if the amount is 20,230, it will total the amount as 20.00. it work real fine if the number is only 20230 without the ','. help me please.
function checkedAll () {
var row_counter =0;
$("input[id ^= 'check_'] ").each(function() {
row_counter++;
});//en
var total=0;
for(var i=1; i<=row_counter; i++) {
//alert(i);
if (document.getElementById("checkall").checked==true){
document.getElementById('check_'+i).checked = true;
var amaun = document.getElementById('amaun_'+i).value;
//alert(amaun);
total = parseFloat(total)+parseFloat(amaun);
}
else{
document.getElementById('check_'+i).checked = false;
var amaun = 0;
total = parseFloat(total)+parseFloat(amaun);
}
}
document.getElementById("jum_baucar").value=total.toFixed(2);
}
function calcTotal(){
//alert("here");
var row_counter =0;
$("input[id ^= 'check_'] ").each(function() {
row_counter++;
});//en
var total=0;
for(var i=1; i<=row_counter; i++) {
//alert(i);
if (document.getElementById('check_'+i).checked == true){
var amaun = document.getElementById('amaun_'+i).value;
//alert(amaun);
total = parseFloat(total)+parseFloat(amaun);
}
else{
var amaun = 0;
total = parseFloat(total)+parseFloat(amaun);
}
}
document.getElementById("jum_baucar").value=total.toFixed(2);
}
Those are my js code.
what should I add into it?
Having a , in a number that is applied with parseFloat() treats it as a decimal. For example parseFloat('10,10') => 10. One simple solution is simply removing the , from the string:
amaun = amaun.replace(',',''); // Replace a comma with nothing
Or for several commas using a regexp to act as a "replaceAll()":
amaun = amaun.replace(RegExp(',','g'),'');
Then you can apply parseFloat(amaun):
total = parseFloat(total)+parseFloat(amaun);

How to get input box values and the select box values to store it in array and do calculation

I'm trying to get input box values and select box values to store it each one in array and do some calculation and I couldn't get a result here is my javascript code:-
$(window).on('pageinit', function() {
$(document).ready(function(){
$("#Scal").click(function() {
var x = parseFloat($('[name^="Sc"]').val()) || 0
var y = parseFloat($('[name^="Sgrade"]').val()) || 0
var sum1 = 0;
var sum2 = 0;
for(var i=0; i< x.length; i++) {
sum1 += x[i]*y[i];
sum2 += x[i];
}
var sum3 = sum1/sum2
var sum3 = sum3.toFixed(2)
$('#Sres').val(sum3)
});
});
});
You need to loop over the elements from which you're pulling the values. Your parseFloat approach isn't going to work.
Do something like this to get the sum of all Sc values:
$(document).ready(function () {
var sumSc = 0;
$("#Scal").click(function () {
//loop over the matching elements with jQuery each()
$('[name^="Sc"]').each(function () {
sumSc += +$(this).val(); //the extra "+" here coerces a Number value
});
console.log(sumSc); //this outputs your total in the console
});
});
You can apply that same approach to sum the other elements and do your calculations.

jquery counting inside input with custom value

I have a basic counter that counts up within an input field. this works exactly how I want it to. The problem I am facing is that I can only set the target number via the input value. i want to be able to set this via a js variable, ignoring the html input value
DEMO http://jsfiddle.net/vyN6V/238/
Current jQuery
var number = 827;
function count(Item){
var current = parseInt(Item.val());
Item.val(current +=5);
if(current < number){
setTimeout(function(){count(Item)}, 0.1);
}
}
count($(".input"));
Desired jQuery (doesn't work)
var number = 827;
var aValue = 500;
function count(Item){
var current = aValue;
Item.val(current +=5);
if(current < number){
setTimeout(function(){count(Item)}, 0.1);
}
}
count($(".input"));
Should work, you just forgot to add 5 to aValue:
var current = aValue;
aValue+=5;
Your current is inside your function, it works if you simply use aValue:
Item.val(aValue += 5);
Fiddle
this would solve the problem: http://jsfiddle.net/Jg6LN/1/
var number = 827;
var aValue = 500;
function count(Item, value){
var current = value || parseInt(Item.val());
Item.val(current +=5);
if(current < number){
setTimeout(function(){count(Item)}, 0.1);
}
}
count($(".input"), aValue);
What about this?
var aValue = 500;
var number = 827;
function count(Item) {
var current = parseInt(Item.val()) || aValue;
Item.val(current + 5);
if (Item.val() < number) {
setTimeout(function () {
count(Item)
}, 0.1);
}
}
count($(".input"));
http://jsfiddle.net/vyN6V/242/

Add all values with input name="TotalInline[]"

How to add values from all input with name name="TotalInline[]"?
The following does not seams to work:
var total = 0;
$.each('input[name="TotalInline[]"];,function() {
total += this;
});
This should work :
var total = 0;
$('input[name="TotalInline"]').each(function() {
// assuming you have ints in your inputs, use parseFloat if those are floats
total += parseInt(this.value, 10);
});
var total = 0;
$.each($('input[name="TotalInline[]"]'), function() {
total += parseInt(this.value, 10);
});
You have some serious syntax errors, try this:
var total = 0;
$('input[name="TotalInline[]"]').each(function () {
total += parseInt(this.value, 10);
});
Try like this...
var total = 0;
$('input[name="TotalInline[]"]').each(function() {
total += parseInt($(this).val(),10);
});
var total = 0;
$('input[name="TotalInline[]"]').each(function() {
total += +this.value.replace(/[^\d.]/g, '');
});
Uses a quick regex to filter out only the numbers (and decimal point).
Uses a + prefix to convert to a number.

Categories

Resources