I seem to have trouble calculating some numbers together. When I want to use:
for (var key in week_total) {
$("." + key).html(week_total[key]);
}
I am getting a NaN and thereforce every group has a NaN. Is this the right way of even using week_total[group] = week_total[group] + work_minutes;?
My script:
drawCallback: function (settings) {
var api = this.api(), data;
var rows = api.rows({page: 'current'}).nodes();
var last = null;
var week_total = new Array;
api.column(weekColumn, { page: 'current' }).data().each(function (group, i) {
var work_hours = api.column(hourColumn).data()[i].split(':');
var work_minutes = (+ work_hours[0]) * 60 + (+ work_hours[1]);
week_total[group] = week_total[group] + work_minutes;
if (last !== group) {
$(rows).eq(i).before('<tr><td colspan="5">{{ trans('admin.worktime.field.week') }} ' + group + '</td><td colspan="3" style="font-style:italic;" class="' + group + '"></td></tr>');
last = group;
}
});
for (var key in week_total) {
$("." + key).html(week_total[key]);
}
var array = {
work_month: work_month,
work_year: work_year
};
history.pushState(null, null, '?' + $.param(array));
drawDataTable(this);
}
I think, problem is in not initialized week_total array.
Calculating should be like
week_total[group] = week_total[group]
? week_total[group] + work_minutes
: work_minutes;
If week_total[group] is undefined then week_total[group] + 1 will be NaN
Related
For my chrome extension, I have a function called storeGroup that returns an object. However, in function storeTabsInfo, when I call storeGroup and set it equal to another object, the parts inside the object are undefined. The object is being populated correctly in storeGroup, so I'm not sure why it's undefined?
function storeTabsInfo(promptUser, group)
{
var tabGroup = {};
chrome.windows.getCurrent(function(currentWindow)
{
chrome.tabs.getAllInWindow(currentWindow.id, function(tabs)
{
/* gets each tab's name and url from an array of tabs and stores them into arrays*/
var tabName = [];
var tabUrl = [];
var tabCount = 0;
for (; tabCount < tabs.length; tabCount++)
{
tabName[tabCount] = tabs[tabCount].title;
tabUrl[tabCount] = tabs[tabCount].url;
}
tabGroup = storeGroup(promptUser, group, tabName, tabUrl, tabCount); // tabGroup does not store object correctly
console.log("tabGroup: " + tabGroup.tabName); // UNDEFINED
chrome.storage.local.set(tabGroup);
})
})
}
function storeGroup(promptUser, group, name, url, count)
{
var groupObject = {};
// current count of group
var groupCountValue = group.groupCount;
var groupName = "groupName" + groupCountValue;
groupObject[groupName] = promptUser;
var tabName = "tabName" + groupCountValue;
groupObject[tabName] = name;
var tabUrl = "tabUrl" + groupCountValue;
groupObject[tabUrl] = url;
var tabCount = "tabCount" + groupCountValue;
groupObject[tabCount] = count;
var groupCount = "groupCount" + groupCountValue;
groupObject[groupCount] = groupCountValue + 1;
// successfully shows parts of groupObject
console.log("Final group: " + groupObject[groupName] + " " + groupObject[tabName] + " " + groupObject[tabUrl] + " " + groupObject[tabCount] + " " + groupObject[groupCount]);
return groupObject;
}
As i said in the comment above you created the groupObject dict keys with the group count so you should use it again to access them or remove it, if you want to use it again although i think this isnt necessary so use:-
... ,tabGroup[tabName + group.groupCount]...
But if you want to get it easily as you wrote just write this code instead of your code:-
function storeGroup(promptUser, group, name, url, count)
{
var groupObject = {};
// current count of group
groupObject['groupName'] = promptUser;
groupObject['tabName'] = name;
groupObject['tabUrl'] = url;
groupObject['tabCount'] = count;
groupObject['groupCount'] = group.groupCount + 1;
// successfully shows parts of groupObject
console.log("Final group: " + groupObject['groupName'] +
" " + groupObject['tabName'] + " " + groupObject['tabUrl'] +
" " + groupObject['tabCount'] + " " +
groupObject['groupCount']);
return groupObject;
}
I'm having trouble updating the total when I change the "Complete E-Book" product quantity. When I first set the quantity and add it to basket it shows the correct total within the basket but when I change the quantity it adds on to the previous total. Overall I want to be able to add multiple products to the basket total (reason for x += p2Total (x var is what holds the total - Line 86) but while allowing for the Quantity of the product to be changed and then updated in the total.
Codepen Here >
Products in question are the top 2
JS:
// JQuery Functions for NavBar - Class Toggle
(function() {
$('.hamburger-menu').on('click', function() {
$('.bar').toggleClass('animate');
})
})();
(function() {
$('.hamburger-menu').on('click', function() {
$('.bar2').toggleClass('ApprDown');
})
})();
/*
START OF BASKET
START OF BASKET
*/
// Get access to add to basket basket button
var addToBasket = document.querySelector('.atbb');
addToBasket.addEventListener('click', P1);
// Formatter simply formats the output into a currceny format istead of a general number format. This is using the ECMAScript Internationalization API
var formatter = new Intl.NumberFormat('en-US', {
style: 'currency',
currency: 'GBP',
minimumFractionDigits: 2,
});
var totalBasket
var discountLimit = 10
var discount = 3.50
var x = 0.00
// One big function with different condtions based on the differnt products and then simply concatinate the values where needed
function P1() {
var y = document.getElementById("p1Quant").value;
if (+y > discountLimit) {
var z = 15.000
x = parseFloat(+y) * parseFloat(+z); // + will convert the vars into Numbers etc
document.getElementById("BasketSumData").innerHTML = ("Sub Total: ") + formatter.format(x) + ("<br/>") + ("<hr />") + ("<div class='strike'>Plus £3.50 Delivery</div>") + ("<br/>") + ("<hr />") + ("Total: ") + formatter.format(x)
// Jquery Notificaiton
var truckVar = document.getElementById("truck");
truckVar.setAttribute("class", "animateTruck");
} else if (+y <= 0) {
document.getElementById("BasketSumData").innerHTML = ("Sub Total: ") + formatter.format(0) + ("<br/>") + ("Total: ") + formatter.format(0)
} else {
var z = 15.000
var s = 15.000
x = parseFloat(+y) * parseFloat(+z) + 3.50
var sub = parseFloat(+y) * parseFloat(+s)
document.getElementById("BasketSumData").innerHTML = ("Sub Total: ") + formatter.format(sub) + ("<br/>") + ("<hr />") + ("Plus £3.50 Delivery") + ("<br/>") + ("<hr />") + ("Total: ") + formatter.format(x)
}
}
var addToBasket2 = document.querySelector('.atbb2');
addToBasket2.addEventListener('click', P2);
function P2() {
p2Total = 0.00
var y = document.getElementById("p2Quant").value;
var p2 = 8.00
var p2Total = parseFloat(+y) * parseFloat(+p2); // + will convert the vars into Numbers etc
// var totalBasket = + x + x // javascript add value onto set var
x += p2Total // Append the amount to the basket
document.getElementById("BasketSumData").innerHTML = ("Sub Total: ") + formatter.format(x) + ("<br/>") + ("<hr />") + ("<div class='strike'>Plus £3.50 Delivery</div>") + ("<br/>") + ("<hr />") + ("Total: ") + formatter.format(x)
if (+y <= 0) {
p2Total = 0.00
}
}
Don't add the value to x, add x and p2Total into a new temporary value that is scoped to the function itself and use that.
var tmp_total = x + p2Total;
document.getElementById("BasketSumData").innerHTML = ("Sub Total: ") + formatter.format(tmp_total) + ("<br/>") + ("<hr />") + ("<div class='strike'>Plus £3.50 Delivery</div>") + ("<br/>") + ("<hr />") + ("Total: ") + formatter.format(tmp_total)
var swTitle = {};
var favorite = [];
$.each($("input[name='Title']:checked"), function() {
favorite.push($(this).val());
console.log($("input[name='Title']:checked"));
});
swTitle.domain = favorite;
var List = {};
for (var m = 0; m < favorite.length; m++) {
var swTitleObj = [];
$.each($('input[name="' + swTitle.domain[m] + '"]:checked'), function() {
console.log(swTitle.domain[m]);
swTitleObj.push($(this).attr("class"));
console.log(swTitleObj);
});
List[swTitle.domain[m]] = swTitleObj;
}
var swSkillData = " ";
$.each(List, function(key, value) {
console.log(key + ":" + value);
swSkillData += '<li>' + key + ' ' + ':' + ' ' + value + '</li>';
});
Output will be like:
Fruits:Apple,Banana,Orange,Grapes
I want my output be like:
Fruits:Apple,Banana,Orange & Grapes
I have an array of keys and values separated by commas. I want to insert "and" and remove the comma before the last checked element. Kindly help me out with this issue.
I think you can reduce your code, with an option of adding and before the last element like,
var inputs=$("input[name='Title']:checked"),
len=inputs.length,
swSkillData='',
counter=0;// to get the last one
$.each(inputs, function() {
sep=' , '; // add comma as separator
if(counter++==len-1){ // if last element then add and
sep =' and ';
}
swSkillData += '<li>' + this.value + // get value
' ' + ':' + ' ' +
this.className + // get classname
sep + // adding separator here
'</li>';
});
Updated, with and example of changing , to &
$.each(List, function(key, value) {
console.log(key + ":" + value);
var pos = value.lastIndexOf(',');// get last comma index
value = value.substring(0,pos)+' & '+value.substring(pos+1);
swSkillData += '<li>' + key + ' ' + ':' + ' ' + value + '</li>';
});
Snippet
var value ='Apple,Banana,Orange,Grapes';var pos = value.lastIndexOf(',');// get last comma index
value = value.substring(0,pos)+' & '+value.substring(pos+1);
console.log(value);
Here is an easy and customizable form of doing it.
(SOLUTION IS GENERIC)
$(document).ready(function() {
var ara = ['Apple','Banana','Orange','Grapes'];
displayAra(ara);
function displayAra(x) {
var str = '';
for (var i = 0; i < x.length; i++) {
if (i + 1 == x.length) {
str = str.split('');
str.pop();
str = str.join('');
str += ' and ' + x[i];
console.log(str);
$('.displayAra').text(str);
break;
}
str += x[i] + ',';
}
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Fruits : <span class="displayAra"></span>
str = str.replace(/,(?=[^,]*$)/, 'and')
I solved my own issue. I replaced my last comma with "and" using the above regex. Thanks to Regex!!!
I'm trying to build a simple site that will check and print out "Buy It Now Prices" for cars. I can't get the JavaScript push function to print out anything but strings.
The eBay API says that buyItNowPrice returns an Amount.
I have experimented with the other Item functions, and the only ones that are working for me are ones that return a String.
The question is, how should the line var itemPrice = item.buyItNowPrice; be formatted to output a number?
function _cb_findItemsByKeywords(root) {
var items = root.findItemsByKeywordsResponse[0].searchResult[0].item || [];
var html = [];
html.push('<table width="100%" border="0" cellspacing="0" cellpadding="3"><tbody>');
for (var i = 0; i < items.length; ++i) {
var item = items[i];
var title = item.title;
var pic = item.galleryURL;
var viewitem = item.viewItemURL;
var itemPrice = item.buyItNowPrice;
var timeLeft = item.watchCount;
if (title != null && null != viewitem) {
html.push('<tr><td>' + '<img src="' + pic + '" border="1">' + '</td>' +
'<td><a href="' + viewitem + '" target="_blank">' +
title + '</a>' // end hyperlink
+
'<br>Item Price: ' + itemPrice +
'<br>Time Remaining: ' + timeLeft +
'</td></tr>');
}
}
html.push('</tbody></table>');
document.getElementById("results").innerHTML = html.join("");
}
// Create a JavaScript array of the item filters you want to use in your request
var filterarray = [{
"name": "MaxPrice",
"value": "250000",
"paramName": "Currency",
"paramValue": "USD"
},
{
"name": "MinPrice",
"value": "15000",
"paramName": "Currency",
"paramValue": "USD"
},
//{"name":"FreeShippingOnly", "value":"false", "paramName":"", "paramValue":""},
{
"name": "ListingType",
"value": ["AuctionWithBIN", "FixedPrice", /*"StoreInventory"*/ ],
"paramName": "",
"paramValue": ""
},
];
// Generates an indexed URL snippet from the array of item filters
var urlfilter = "";
function buildURLArray() {
for (var i = 0; i < filterarray.length; i++) {
var itemfilter = filterarray[i];
for (var index in itemfilter) {
// Check to see if the paramter has a value (some don't)
if (itemfilter[index] !== "") {
if (itemfilter[index] instanceof Array) {
for (var r = 0; r < itemfilter[index].length; r++) {
var value = itemfilter[index][r];
urlfilter += "&itemFilter\(" + i + "\)." + index + "\(" + r + "\)=" + value;
}
} else {
urlfilter += "&itemFilter\(" + i + "\)." + index + "=" + itemfilter[index];
}
}
}
}
}
buildURLArray(filterarray);
// Construct the request
var url = "http://svcs.ebay.com/services/search/FindingService/v1";
url += "?OPERATION-NAME=findItemsByKeywords";
url += "&SERVICE-VERSION=1.0.0";
url += "&SECURITY-APPNAME=REDACTED";
url += "&GLOBAL-ID=EBAY-MOTOR";
url += "&RESPONSE-DATA-FORMAT=JSON";
url += "&callback=_cb_findItemsByKeywords";
url += "&REST-PAYLOAD";
//url += "&categoryId=6001";
url += "&keywords=Ferrari 575";
url += "&paginationInput.entriesPerPage=12";
url += urlfilter;
// Submit the request
s = document.createElement('script'); // create script element
s.src = url;
document.body.appendChild(s);
You are reading the wrong eBay documentation. FindItemsByKeywords is part of the Finding API service. The buyItNowPrice field is found in the item.listingInfo field. Changing the code to the following will output the price.
var itemPrice = '---';
// buyItNowPrice may not be returned for all results.
if(item.listingInfo[0].buyItNowPrice) {
itemPrice = item.listingInfo[0].buyItNowPrice[0]['#currencyId'] + ' ' + item.listingInfo[0].buyItNowPrice[0].__value__;
} else if(item.sellingStatus[0].currentPrice) {
itemPrice = item.sellingStatus[0].currentPrice[0]['#currencyId'] + ' ' + item.sellingStatus[0].currentPrice[0].__value__;
}
This may be a dumb question but I can't seem to get it or find it anywhere.
I have a .each function that returns the id's of a bunch of divs on a page and then assigns them a number. I need them to be outputted in a specific format all as one string so I can pass them to a database and use them as "sort_order" values. (I split them through a sproc in my database).
Here is my code:
jQuery('#updateAllContentButton').click(function() {
var count = 1;
jQuery('.CommentaryItem').each(function() {
var id = GetID(jQuery(this));
var data_str = (id + ':' + count + '~');
console.log(data_str);
count++;
});
});
So that returns each data_str on a separate line but I need it to return it like this:
144:2~145:3~146:4~147:4~148:5 (so on)
Any help would be appreciated, thanks!
Use map and join :
jQuery('#updateAllContentButton').click(function() {
console.log(jQuery('.CommentaryItem').map(function(i) {
return GetID(jQuery(this)) + ':' + (i+1);
}).get().join('~'));
});
Note that you don't have to count yourself : Most jQuery iteration functions do it for you.
You can use an array for that. Like this...
jQuery('#updateAllContentButton').click(function() {
var count = 1;
var arr = [];
jQuery('.CommentaryItem').each(function() {
var id = GetID(jQuery(this));
var data_str = (id + ':' + count + '~');
arr.push(data_str);
//console.log(data_str);
count++;
});
console.log(arr.join());
});
try this:
jQuery('#updateAllContentButton').click(function() {
var count = 1;
var data_str = "";
jQuery('.CommentaryItem').each(function() {
var id = GetID(jQuery(this));
data_str += (id + ':' + count + '~');
console.log(data_str);
count++;
});
});
change
var data_str = (id + ':' + count + '~');
to
data_str+ = (id + ':' + count + '~');
full code
jQuery('#updateAllContentButton').click(function() {
var count = 1,
data_str;
jQuery('.CommentaryItem').each(function() {
var id = GetID(jQuery(this));
data_str += (id + ':' + count + '~');
console.log(data_str);
count++;
});
});