Looping thought a javascript / JQuery array and getting a 'grand' total - javascript

Ok, I have been working on this for some time, I have some close to getting it to work but not completely. So what I am doing is adding the value from a weekly input form into an array with its key.
There will be no limit on the number of rows as I can (and this works fine) AJAX add a row to the form with a button.
I currently add all the totals for each day together, this works, as all the Mondays have a .Monday class on them (I can post that code it need, please just ask) and each other day.
I have also got an id on each input which as the day of the week and a count, so #Monday0, #Monday1, same for each day and each row ect.
Now what I am doing with the code below, is to add the week up and then display that (console log for now) in that weeks row. So I want to add all the daily ids, Monday though to Sunday that end in 0, then do the same for 1 and so on.
var LoadHourTotals = function() {
$('.TimebreakdownInput').change(function() {
var InputArrays = []; //Array to store all weekly inputs
var Totals = []; //Store Array total for display
GetCurrentID = $(this).attr('id');
CurrentCount = GetCurrentID.charAt(GetCurrentID.length-1)
var WeeklyArray = ["Monday"+CurrentCount,"Tuesday"+CurrentCount,"Wednesday"+CurrentCount,"Thursday"+CurrentCount,"Friday"+CurrentCount,"Saturday"+CurrentCount,"Sunday"+CurrentCount];
$.each(WeeklyArray, function(k, v) {
var values = parseFloat( $('#'+v).val() );
if (isNaN(values)) { values = 0; } //Set value to 0 if its not a number
if (!values) { values = 0; }
InputArrays.push({ key: CurrentCount, hours:values });
});
console.log(InputArrays);
//$('.TimebreakdownTotalHours').html(Totals); //Display / Add total into HTML
});
} //End of LoadHourTotals function
I think I am close with this, each daily input is saved into its own array with a key count and its value for that day. For example, 0:XX 0:XX (this seven times, all for the 1st row). This is then repeated for each row as needed.
If what I have done is not right or there is a better method for doing this, then please let me know.
But now what I need to do is go though each key, take its value, getting a 'grand' total for all seven inputs, then display or save that total into a new array (which is what I was trying to do) then display / console log each weekly total.
I have gone though a number of posts on here but I could not find anything that fits for my problem.
All help very welcome.
If I have not posted some code that is need then please let me know.
Please let me know if I have not explained myself right.
Many Thanks.

Its ok, I have found an answer. I tried this but it did not work,
var total = 0;
$.each(InputArrays,function() {
total += this;
console.log(total);
});
But some playing around with the code, I console loged 'this' and tried the following which now seems to work. Thanks
var total = 0;
$.each(InputArrays,function() {
total += this.hours;
console.log(total);
});

Related

Datetime array to array with dates, get corresponding time afterwards

Specific situation.. I'm having an array filled with datetimes I pull in via an api.
Users should be able to select a date from a datepicker (only showing dates available in the array) and afterwards see the corresponding time.
So what I've done..
The original array is obtained via php, so before starting to populate the datepicker with possible dates I create an extra array with dates only.
Since I maintain the key's it's possible to put these 2 arrays next to eachother.
Array looks as following:
["8-8-2017,07:00", "26-8-2017,07:00"];
So far so good...
After a user picks a date I trigger this to be able to start digging for the time corresponding that date.
Now it's getting messy...
$('#datepick').datepicker().on("input change", function(e) {
$("#uur").text('');
var selecteddate = e.target.value;
var searchArr = datesArray;
var ind = searchArr.indexOf(selecteddate.toString());
var result = datesArray.filter(function(item) {
return typeof item == 'string' && item.indexOf(selecteddate.toString()) > -1;
});
var afterComma = result.toString().substr(result.toString().indexOf(",") + 1);
var final = afterComma.replace(":", "u");
$("#uur").text("De warming up party gaat van start rond " + final);
});
The result is that this only works on the last element of the array.
Because I'm splitting based on the comma's. Now I know the easiest way to work arround this would be to change the , that's seperating date and time in another symbol but still I'm wondering why this couldn't be easier.
You convert whole array to string every time. You should change following code:
var afterComma = result.toString().substr(result.toString().indexOf(",") + 1);
To this;
var afterComma = item.toString().substr(item.toString().indexOf(",") + 1);
Edit:
I also missed the loop above
//for every item in result, afterComma will refer to related minute string
for (var item in result) {
var afterComma = item.toString().substr(item.toString().indexOf(",") + 1);
// Do rest here
}

count how many data in array and increment javascript

I'm new in stackoverflow:
Here is my issue, i would like to count how many tickets by month a user has and push it in my array,
i did that:
for(j=0; j< data.data.tickets.length ;j++){
var requesterid = data.data.tickets[j].requester_id;
var created_at = data.data.tickets[j].created_at;
var today = new Date().toISOString().slice(0, 7);
if(created_at.includes(today)&& requesterid == cleartab[requesterid]['id']){total ++}
var arrayRef2 = cleartab[requesterid]['monthly'] || [];
cleartab[requesterid]['monthly'] = arrayRef2.concat([{"janvier":total}], [{"fevier":"fef"}]);
}
The problem is that it gave me wrong result.
Here is my array:
My array
If my question is not clear, i can re-explain or tell me if you need something more to answer it
I hope you can help me
My issue:
Some people should not have ticket the result is not the good one. I would like to be sure that it increment only one people when 1 ticket has been sent in the current month. For now, when someone send a ticket in the current month, every user got +1 ticket in the current month. But what i want is that: it increment only for one user, the user who sent the ticket. Is that clear ?
Based on my understanding of the problem, you could try as below:
for(j=0; j< data.data.tickets.length ;j++){
var requesterid = data.data.tickets[j].requester_id;
var created_at = data.data.tickets[j].created_at;
var today = new Date().toISOString().slice(0, 7);
// read the monthly for a given requestor or
// initialize the new array by setting the total
// to 0 "janvier:0
var arrayRef2 = cleartab[requesterid]['monthly'] ||
[{"janvier":0}, {"fevier":"fef"}];
if(created_at.includes(today) &&
requesterid == cleartab[requesterid]['id']){
// increment the total, very first time the value of
// arrayRef2[0].janvier will be zero, but in
// next iteration it will be always the previous value
arrayRef2[0].janvier++;
}
cleartab[requesterid]['monthly'] = arrayRef2;
}

Send text to specific li in an array

I have a number of li items in a ul. I need to add all of the li items to an array, then loop through the array and sum a value that is in each li.
The value is for the number of hours that item will take. So item one might be 2 hours, item two might be 5 hours.
For every 7.5 hours, I need to add 1 day to the day field in each li. So item 1,2 and 3 will display day 1. Items 4,5,6 and 7 will display day 2 etc.
Here is what I have so far:
list array:
var list = document.getElementById("dropArea").getElementsByTagName("li");
Number of Hours:
var hrsArray = $("#sortable2 li").find("#hrsSpan").map(function () { return $(this).text() }).get();
var lengthArr = hrsArray.length;
for (var i = 0; i < lengthArr; i++) {
hrsArray[i] = hrsArray[i].replace("Hours - (", "");
hrsArray[i] = hrsArray[i].replace(")", "");
}
And here is were I count the total number of hours. I can send "1" to the day span in each li, but I can't figure out how to look at the li's on an individual basis:
//Add all the hrs together to get the total
for (var i in hrsArray) {
total += hrsArray[i];
//alert(list[i].toString());
//Object found at this point, need to figure out how to send text to day span in it.
if (total / 7.5 <= 1) {
$('#sortable2 li').find('#day').html('1');
}
}
$('#sortable2 li').find('#day')
This creates a set with all the matched objects, to retrieve a specific object use .get(index).
http://api.jquery.com/get/
$('#sortable2 li').find('#day').get(i).html('1');
To avoid rebuilding the set on every iteration, I would store it in a variable outside of the loop.
//Add all the hrs together to get the total
var $dayFields = $('#sortable2 li').find('#day');
for (var i in hrsArray) {
total += hrsArray[i];
//alert(list[i].toString());
//Object found at this point, need to figure out how to send text to day span in it.
if (total / 7.5 <= 1) {
$($dayFields.get(i)).html('1');
}
}
EDIT:
A better way to approach this would be to loop over each li instead of an array of hours:
$("#sortable2 li").each(function() {
$(this).find("hrsSpan"); // This selects the hours field
$(this).find("day"); // This selects the day field in the same li
});
When you do $('#sortable2 li').find('#day').html('1'); you lose the jquery object on the find. You would need to wrap it in the $() again. Here's a simpler way to do it without having to use find.
$("#sortable2 #day").html(1)
Heres an example of it working http://jsfiddle.net/9nutmuvm/

Calculate total after retriveing tax rate from JSON

I have 1 select, 2 text inputs & some JSON data in a form:
select input: List of Suppliers
text input 1: Net Amount
text input 2: Gross Amount
JSON Data:contains the rates of various suppliers as JSON in supplier_tax_rates
I am calculating Gross Amount something like this(pseudo code):
grossAmount = NetAmount + ((currently_selected_supplier.tax_percentage_charged / 100) * netAmount)
Here is the complete code:
Calculate total after retriveing tax rate from JSON
Now, this should work but it doesn't. I get NaN(not a number), means something is wrong. But I have trouble find where.
JSfiddle
You have multiple problems in your code. Here is the correct version:
var taxRates = $.parseJSON(supplier_tax_rates);
var getTaxRate = function(id) {
for (var i in taxRates) { // correct loop definition
if (taxRates[i].id == id) { // check you get id correctly
return taxRates[i].tax_percentage_charged; // instead of 'rate'
}
}
};
$('#PurchaseNetAmount').on('change', function(event) {
var taxRatesId = $('#PurchaseSupplierId').val();
var netAmount = parseFloat(this.value);
var grossAmount = netAmount + ((getTaxRate(taxRatesId) / 100) * netAmount);
$('#PurchaseGrossAmount').val(grossAmount);
});
DEMO: http://jsfiddle.net/A9vmg/18/
Your problem is in the look up function.
for(TaxRate in supplier_tax_rates ){
supplier_tax_rates is a string, not a JSON object
Than after you fix that you will have another error
return rate;
What is rate?
Learn to use console.log() or breakpoints so you can step throught your code and debug it.
getTaxRate(taxRatesId) return undefined

jQuery - totalling up the value of several numeric <select> elements?

I have a form that asks for addresses. After each address, we ask how long the person has lived in that address, with <select> dropdowns for Years and Months.
I have a jQuery event each time the <select> is changed:
var prev_addresses = 0;
$('select.months, select.years').change(function() {
// Calculate total months
var months = $('select.months').val();
var years = $('select.years').val();
var total_months = parseInt(months) + parseInt(years*12); // We parseInt() to avoid concatenation
console.log('Total months: '+total_months);
if(total_months < 12) {
// Find the next div.hidden-address
prev_addresses = prev_addresses+1;
console.log('Number of previous addresses: '+prev_addresses);
console.log('');
$('div.hidden-address').clone(true).appendTo('#previous-addresses').slideToggle();
}
});
I want this to keep on happening all the while a person has less than 12 months of addresses. However after the first time the event fires, every time a <select> is updated the console just logs the first set of values (from the original Year and Month selects, even though there are now multiple ones).
I want to total up the values of every <select> element on a page, even after more are added dynamically. How can I do this?
Hope that makes sense, I'm happy to clarify if you need further details.
Thanks,
Jack
Loop through all select boxes, and add the value to a variable, something like this:
var totalMonths = 0;
$('select.months').each(function () {
totalMonths += $(this).val();
});
$('select.years').each(function () {
totalMonths += 12 * $(this).val();
});

Categories