I have a function that sums my values and everything works fine, but only when all inputs have a value entered. However, I would like default to have 0 assigned to it.so that the function works when at least one value is given . How to do it ?.
var DeductiblepercentageM = thisPointer.entity.getValue('number.DeductiblepercentageM[' + i + ']');
var InsuranceLimitM = thisPointer.entity.getValue('number.InsuranceLimitM[' + i + ']');
var insuranceRaitingM = thisPointer.entity.getValue('number.insuranceRaitingM[' + i + ']');
var InsurerNumberM = thisPointer.entity.getValue('number.InsurerNumberM[' + i + ']');
DeductiblepercentageM = DeductiblepercentageM.replace(",", ".");
DeductiblepercentageM = parseFloat(DeductiblepercentageM)
InsuranceLimitM = InsuranceLimitM.replace(",", ".");
InsuranceLimitM = parseFloat(InsuranceLimitM)
insuranceRaitingM = insuranceRaitingM.replace(",", ".");
insuranceRaitingM = parseFloat(insuranceRaitingM)
InsurerNumberM = InsurerNumberM.replace(",", ".");
InsurerNumberM = parseFloat(InsurerNumberM)
//log the outcome of decimal separator change
var positionSum = +(DeductiblepercentageM + InsuranceLimitM +insuranceRaitingM + InsurerNumberM);
jQ('[id="DeductibleM[' + i + ']"]').val(positionSum);
thisPointer.entity.setValue('DeductibleM[' + i + ']', positionSum);
thisPointer.entity.mergeLocal(true);
if (totalSum != "NaN") {
totalSum = +(totalSum + positionSum).toFixed();
}
}
else {
totalSum = "-";
}
According to #Terry
var InsuranceLimitM = thisPointer.entity.getValue('number.InsuranceLimitM[' + i + ']') || 0;
adding || 0 to the end of the code helps and makes the code count right away
Related
I am attaching an excerpt from my code:
document.getElementById("product-selector-25b").onchange = function () {
document.getElementById("purchase-25b").href = "https://example.com/?add-to-cart=" + this.selectedOptions[0].getAttribute('data-product') + "&" + "variation_id=" + this.value + "/";
}
document.getElementById("product-selector-26").onchange = function () {
document.getElementById("purchase-26").href = "https://example.com/?add-to-cart=" + this.selectedOptions[0].getAttribute('data-product') + "&" + "variation_id=" + this.value + "/";
}
document.getElementById("product-selector-29").onchange = function () {
document.getElementById("purchase-29").href = "https://example.com/?add-to-cart=" + this.selectedOptions[0].getAttribute('data-product') + "&" + "variation_id=" + this.value + "/";
}
document.getElementById("product-selector-Zx3").onchange = function () {
document.getElementById("purchase-Zx3").href = "https://example.com/?add-to-cart=" + this.selectedOptions[0].getAttribute('data-product') + "&" + "variation_id=" + this.value + "/";
}
document.getElementById("product-selector-001sfF").onchange = function () {
document.getElementById("purchase-001sfF").href = "https://example.com/?add-to-cart=" + this.selectedOptions[0].getAttribute('data-product') + "&" + "variation_id=" + this.value + "/";
}
As you can see, the code is repeated in everything except IDs getElementById("product-selector-25b") purchase-25b
The problem is that in total I have hundreds of different IDs and I believe that this code can be optimized somehow, but I don’t understand how. What do you advise?
Here is how you can refacto your code :
const selectors = [
"product-selector-25b",
"product-selector-26",
"product-selector-29",
"product-selector-Zx3",
"product-selector-001sfF"
];
const updateLink = (e) => {
const selectorId = e.target.id;
const productId = e.target.selectedOptions[0].getAttribute("data-product");
const variationId = e.target.value;
const purchaseId = `purchase-${selectorId.split("-")[1]}`;
document.getElementById(purchaseId).href = `https://example.com/?add-to-cart=${productId}&variation_id=${variationId}/`;
};
document.addEventListener("DOMContentLoaded", () => {
selectors.forEach(selectorId => {
const element = document.getElementById(selectorId);
if(element){
element.onchange = updateLink;
}else {
console.error(`Element with id ${selectorId} not found`)
}
});
});
Just add others ids to the array.
When you want to optimize a repetitive code, the idea is to create a reusable function and loop inside of it
My solution is this:
var elements = document.querySelectorAll('[id^="product-selector-"]');
var updateLink = function(el) {
var tagId = el.id.replace("product-selector-", "");
document.getElementById("purchase-" + tagId).href = "https://example.com/?add-to-cart=" + this.selectedOptions[0].getAttribute('data-product') + "&" + "variation_id=" + this.value + "/";
}
for (var i=0; i < elements.length; i++) {
elements[i].addEventListener("change", function(){
updateLink(this);
});
}
Note: I assume all IDs start with "product-selector-".
Otherwise you need to create an array which contains all the IDs.
I'm using the following script to export Google Ads data from my account, but I am stuck with Google's pre-set date ranges and can't figure out how/if it's possible to jimmy these. Ideal date range would be year to date, with the report refreshing each day and adding on a fresh day's data, but would also be interested if we can get all time to work.
I'm a coding novice, so apologies in advance.
Script:
function main() {
var currentSetting = new Object();
currentSetting.ss = SPREADSHEET_URL;
// Read Settings Sheet
var settingsSheet = SpreadsheetApp.openByUrl(currentSetting.ss).getSheetByName(SETTINGS_SHEET_NAME);
var rows = settingsSheet.getDataRange();
var numRows = rows.getNumRows();
var numCols = rows.getNumColumns();
var values = rows.getValues();
var numSettingsRows = numRows - 1;
var sortString = "";
var filters = new Array();
for(var i = 0; i < numRows; i++) {
var row = values[i];
var settingName = row[0];
var settingOperator = row[1];
var settingValue = row[2];
var dataType = row[3];
debug(settingName + " " + settingOperator + " " + settingValue);
if(settingName.toLowerCase().indexOf("report type") != -1) {
var reportType = settingValue;
} else if(settingName.toLowerCase().indexOf("date range") != -1) {
var dateRange = settingValue;
} else if(settingName.toLowerCase().indexOf("sort order") != -1) {
var sortDirection = dataType || "DESC";
if(settingValue) var sortString = "ORDER BY " + settingValue + " " + sortDirection;
var sortColumnIndex = 1;
}else {
if(settingOperator && settingValue) {
if(dataType.toLowerCase().indexOf("long") != -1 || dataType.toLowerCase().indexOf("double") != -1 || dataType.toLowerCase().indexOf("money") != -1 || dataType.toLowerCase().indexOf("integer") != -1) {
var filter = settingName + " " + settingOperator + " " + settingValue;
} else {
if(settingValue.indexOf("'") != -1) {
var filter = settingName + " " + settingOperator + ' "' + settingValue + '"';
} else if(settingValue.indexOf("'") != -1) {
var filter = settingName + " " + settingOperator + " '" + settingValue + "'";
} else {
var filter = settingName + " " + settingOperator + " '" + settingValue + "'";
}
}
debug("filter: " + filter)
filters.push(filter);
}
}
}
// Process the report sheet and fill in the data
var reportSheet = SpreadsheetApp.openByUrl(currentSetting.ss).getSheetByName(REPORT_SHEET_NAME);
var rows = reportSheet.getDataRange();
var numRows = rows.getNumRows();
var numCols = rows.getNumColumns();
var values = rows.getValues();
var numSettingsRows = numRows - 1;
// Read Header Row and match names to settings
var headerNames = new Array();
var row = values[0];
for(var i = 0; i < numCols; i++) {
var value = row[i];
headerNames.push(value);
//debug(value);
}
if(reportType.toLowerCase().indexOf("performance") != -1) {
var dateString = ' DURING ' + dateRange;
} else {
var dateString = "";
}
if(filters.length) {
var query = 'SELECT ' + headerNames.join(",") + ' FROM ' + reportType + ' WHERE ' + filters.join(" AND ") + dateString + " " + sortString;
} else {
var query = 'SELECT ' + headerNames.join(",") + ' FROM ' + reportType + dateString + " " + sortString;
}
debug(query);
var report = AdWordsApp.report(query);
try {
report.exportToSheet(reportSheet);
var subject = "Your " + reportType + " for " + dateRange + " for " + AdWordsApp.currentAccount().getName() + " is ready";
var body = currentSetting.ss + "<br>You can now add this data to <a href='https://www.optmyzr.com'>Optmyzr</a> or another reporting system.";
MailApp.sendEmail(EMAIL_ADDRESSES, subject, body);
Logger.log("Your report is ready at " + currentSetting.ss);
Logger.log("You can include this in your scheduled Optmyzr reports or another reporting tool.");
} catch (e) {
debug("error: " + e);
}
}
function debug(text) {
if(DEBUG) Logger.log(text);
}
I've tried overwriting the data validation in the host spreadsheet, but think I need to amend the script itself also.
I have a function which I will be using many times, just with a different values.
$('.switch').click(function() {
var frontImg = $('#frontImg');
var frontImg1 = FrontImagePath + darkImageID + ".png";
var frontImg2 = FrontImagePath + frontImageID + ".png";
frontImg.attr('src', frontImg.attr('src') == frontImg1 ? frontImg2 : frontImg1);
var sideImg = $('#sideImg');
var sideImg1 = FrontImagePath + darkSideID + ".png";
var sideImg2 = FrontImagePath + sideImageID + ".png";
sideImg.attr('src', sideImg.attr('src') == sideImg1 ? sideImg2 : sideImg1);
});
Is it possible to re-do it/make it shorter, so I can use it for a different .click() event, by just changing var values.
Try this:
function addClick(e) {
e.click(function() {
var frontImg = $('#frontImg');
var frontImg1 = FrontImagePath + darkImageID + ".png";
var frontImg2 = FrontImagePath + frontImageID + ".png";
frontImg.attr('src', frontImg.attr('src') == frontImg1 ? frontImg2 : frontImg1);
var sideImg = $('#sideImg');
var sideImg1 = FrontImagePath + darkSideID + ".png";
var sideImg2 = FrontImagePath + sideImageID + ".png";
sideImg.attr('src', sideImg.attr('src') == sideImg1 ? sideImg2 : sideImg1);
});
}
I have a form which passes a number of parameters. So far, the stock parameters are being passed:
var params = "title=" + document.getElementById("title").value +
"&url=" + document.getElementById("url").value +
"&snippet=" + document.getElementById("snippet").value +
"&tags=" + document.getElementById("tags").value +
"&status_bookmark=" + document.getElementById("status_bookmark").value +
"&comment=" + document.getElementById("comment").value +
"&status_comment=" + document.getElementById("status_comment").value;
I'm attempting to append additional form elements to this parameter string, which are:
var i, lng = document.getElementById('addbookmark').length;
// If the length property is undefined, then there is only one checkbox.
if (typeof lng === "undefined") {
params + "&topic-link-item-1=" + document.getElementById("topic-link-item-1").value;
params + "&topic-link-comment-box-1=" + document.getElementById("topic-link-comment-box-1").value;
}
else {
for (i = 0; i < lng; i++) {
params + "&topic-link-item-" + i + "=" + document.getElementById("topic-link-item-" + i).value;
params + "&topic-link-comment-box-" + i + "=" + document.getElementById("topic-link-comment-box-" + i).value;
}
}
Here, I've used code taken from another StackOverflow article, and as you can see, I'm trying to build up a series of paired parameters that match the ad hoc form elements I'm generating elsewhere via jQuery, which works.
However, these values appear not be getting passed via the form, while the other form elements are being passed.
Any suggestions?
Update
I've revised the code, per the suggestions, but it's not working:
var i, formObj = document.form['addbookmark'], formObjLng = document.form['addbookmark'].length;
// If the length property is undefined, then there is only one checkbox.
if ((typeof formObjLng !== "undefined")) {
for (i = 0; i < formObjLng; i++) {
if ((formObj.elements['topic-link-item-' + i].type == "checkbox") && (formObj.elements['topic-link-item-' + i].checked)) {
params = params + "&topic-link-item-" + i + "=" + encodeURIComponent(document.getElementById("topic-link-item-" + i)).value;
params = params + "&topic-link-comment-box-" + i + "=" + encodeURIComponent(document.getElementById("topic-link-comment-box-" + i)).value;
}
}
}
As for the form, it's simply a form with an ID of "addbookmark", and to again state what I said earlier, everything else works with the exception of what Im attempting here.
There are 2 issues with your code. You need to URL encode the values using the encodeURIComponent function. Also you need to assign the result back to the params variable when concatenating:
var params =
"title=" + encodeURIComponent(document.getElementById("title").value) +
"&url=" + encodeURIComponent(document.getElementById("url").value) +
"&snippet=" + encodeURIComponent(document.getElementById("snippet").value) +
"&tags=" + encodeURIComponent(document.getElementById("tags").value) +
"&status_bookmark=" + encodeURIComponent(document.getElementById("status_bookmark").value) +
"&comment=" + encodeURIComponent(document.getElementById("comment").value) +
"&status_comment=" + encodeURIComponent(document.getElementById("status_comment").value);
and also for the other values that you are adding:
var i, lng = document.getElementById('addbookmark').length;
// If the length property is undefined, then there is only one checkbox.
if (typeof lng === "undefined") {
params += "&topic-link-item-1=" + encodeURIComponent(document.getElementById("topic-link-item-1").value);
params += "&topic-link-comment-box-1=" + encodeURIComponent(document.getElementById("topic-link-comment-box-1").value);
}
else {
for (i = 0; i < lng; i++) {
params += "&topic-link-item-" + i + "=" + encodeURIComponent(document.getElementById("topic-link-item-" + i).value);
params += "&topic-link-comment-box-" + i + "=" + encodeURIComponent(document.getElementById("topic-link-comment-box-" + i).value);
}
}
Notice how:
params += "&topic-link-item-" + i + "=" + encodeURIComponent(document.getElementById("topic-link-item-" + i).value);
which is equivalent to:
params = params + "&topic-link-item-" + i + "=" + encodeURIComponent(document.getElementById("topic-link-item-" + i).value);
is not the same as what you were doing initially:
params + "&topic-link-item-" + i + "=" + encodeURIComponent(document.getElementById("topic-link-item-" + i).value);
You were simply concatenating 2 values and never assigning the result back to the params variable.
I'm pretty sure Javascript doesnt' allow text append the way you are doing it.
Should be
params = params +
I have been trying for... about 4 hours now lmao.
currentCalc returns 50
currentSum returns 0 when i alert them. Yet I cannot add them together with parseInt????
what am i doing wrong :'(
var identRow = $('tr.identRow');
identRow.each(function () {
var getIdentClass = $(this).attr('class').split(' ').slice(1);
$('tr.ohp' + getIdentClass + ' td.EURm').each(function (index) {
var currentCalc = parseInt($(this).text().replace('.', ''), 10);
var currentSum = $('tr.' + getIdentClass + ' td.totalEURm', this).text().replace('.', '');
total = parseInt(currentCalc, 10) + parseInt(currentSum, 10);
$('tr.' + getIdentClass + ' td.totalEURm').text(total);
if (index == 6) {
alert(total);
}
});
});
EDIT:
Oh goodness. Im completely confused now. I putr the break there. It says total = 50.
I want each iteration to add itself to the total. That is why I add currentCalc to the text of the field im plopping the currentCalc into.
$('tr.' + getIdentClass + ' td.totalEURm').text(total);
with my code now like this:
var identRow = $('tr.identRow');
identRow.each(function () {
var getIdentClass = $(this).attr('class').split(' ').slice(1);
$('tr.ohp' + getIdentClass + ' td.EURm').each(
function (index) {
var currentCalc = parseInt($(this).text().replace('.', ''), 10) || 0;
var currentSum = parseInt($('tr.' + getIdentClass + ' td.totalEURm', this).text().replace('.', ''), 10) || 0;
var total = currentCalc + currentSum;
$('tr.' + getIdentClass + ' td.totalEURm').text(total);
if (index === 6) {
alert(total);
}
});
});
it alerts: 50, then 0, then 50, then 0.
EDIT:
How do I add currentCalc to its last value?
So first iteration its 10, seconds its 20. How do i make it so on the 2nd iteration it equals 30. currentCalc++ is just adding 1 to it.
Now you understand how crap i am :)
I am no expert in JS, but I saw that currentCalc is already an int:
var currentCalc = parseInt($(this).text().replace('.',''), 10);
//...
total = parseInt(currentCalc, 10) + parseInt(currentSum, 10);
so probably the parseInt on an int instead that on a string fails (?)
If you get two alerts, that likely means either your outer or inner .each statements is matching two entries.
If you're using firebug, use console.debug(total); instead of alert(). I recommend using console.debug(this) at some point to make sure it has what you think it has, too. Put it above the alert(). That information would be useful to see.
I do some code formatting and cleanup, try this:
var identRow = $('tr.identRow');
identRow.each(function () {
var getIdentClass = $(this).attr('class').split(' ').slice(1);
$('tr.ohp' + getIdentClass + ' td.EURm').each(
function (index) {
var currentCalc = parseInt($(this).text().replace('.', ''), 10) || 0;
var currentSum = parseInt($('tr.' + getIdentClass + ' td.totalEURm', this).text().replace('.', ''), 10) || 0;
var total = currentCalc + currentSum;
$('tr.' + getIdentClass + ' td.totalEURm').text(total);
if (index === 6) {
alert(total);
}
});
});
I added condition if parseInt fails the vars currentCalc and currentSum will be 0.
Also, like in answer above i'm avoiding double parseInt
Can you give an example html page to try out?
//SUM OF COLUMNS
var total = 0;
var identRow = $('tr.identRow');
identRow.each(function () {
var getIdentClass = $(this).attr('class').split(' ').slice(1);
$('tr.ohp' + getIdentClass + ' td.EURm').each(
function (index) {
var currentCalc = $(this).text().replace('.', '');
total = parseInt(currentCalc)+total;
$('tr.' + getIdentClass + ' td.totalEURm').text(total);
});
});
did the trick.
Now i just gotta set the total to 0 when it gets to the second category because at the moment it keeps adding from where it left off. Progress though. Thanks for everything