this is my first time here as a poster, please be gentle! I have zero knowledge of JS (yet, working on it) but am required to do some JS anyway. Here's my problem. I got some code (not mine) allowing a user to select multiple choices. I found the function that gathers these choices and store them
function getProductAttribute()
{
// get product attribute id
product_attribute_id = $('#idCombination').val();
product_id = $('#product_page_product_id').val();
// get every attributes values
request = '';
//create a temporary 'tab_attributes' array containing the choices of the customer
var tab_attributes = [];
$('#attributes select, #attributes input[type=hidden], #attributes input[type=radio]:checked').each(function(){
tab_attributes.push($(this).val());
});
// build new request
for (var i in attributesCombinations)
for (var a in tab_attributes)
if (attributesCombinations[i]['id_attribute'] === tab_attributes[a])
request += '/'+attributesCombinations[i]['group'] + '-' + attributesCombinations[i]['attribute'];
$('#[attsummary]').html($('#[attsummary]').html() + attributesCombinations[i]['group']+': '+attributesCombinations[i]['attribute']+'<br/>')// DISPLAY ATTRIBUTES SUMMARY
request = request.replace(request.substring(0, 1), '#/');
url = window.location + '';
// redirection
if (url.indexOf('#') != -1)
url = url.substring(0, url.indexOf('#'));
// set ipa to the customization form
$('#customizationForm').attr('action', $('#customizationForm').attr('action') + request);
window.location = url + request;
}
I need to make a simple display summary of these choices. After quite a bit of searching and findling, I came with the line with the DISPLAY SUMMARY comment, this one:
$('#[attsummary]').html($('#[attsummary]').html() + attributesCombinations[i]['group']+': '+attributesCombinations[i]['attribute']+'<br/>')
In the page where I want those options, I added an empty div with the same ID (attsummary):
<div id="attsummary"></div>
Obviously, it is not working. I know I don't know JS, but naively I really thought this would do the trick. May you share with me some pointers as to where I went wrong?
Thank you very much.
Correct form of the line it isn't working for you:
$('#attsummary').html($('#attsummary').html() + attributesCombinations[i]['group']+': '+attributesCombinations[i]['attribute']+'<br/>')
Related
This is the flow I created through Google Apps Script.
Someone writes their information in google form
The information is stored into spreadsheet
Invoice is created within spreadsheet with the newest information received
The invoice is turned into PDF format automatically
The newest invoice is attached to the auto sending email
The person receives an auto-email with the invoice attached as soon as they submit the google form
The problem is that, when someone submits the google form, they receive an invoice but what they receive is the invoice from the information one before. This then repeats. When someone submits, the information inside the invoice is from the person one before.
I am a starter at Google Script so I have no idea why this is happening.
This is the code I use to send the auto email. I have minimized the code.
function for_users2() {
var title = "【お問い合わせありがとうございます】";
var name = '名前';
var mail = 'メールアドレス';
var address = "";
var sheet = SpreadsheetApp.getActiveSheet();
var row = sheet.getLastRow();
var column = sheet.getLastColumn();
var range = sheet.getDataRange();
var TIMESTAMP_LABEL = 'タイムスタンプ';
for (var i = 1; i <= column; i++ ) {
var item = range.getCell(1, i).getValue();
var value = range.getCell(row, i).getValue();
if ( item === TIMESTAMP_LABEL ) {
item = 'お問い合わせ日時';
}
if ( item === 'お問い合わせ日時' ) {
value = Utilities.formatDate(value, 'Asia/Tokyo',"YYYY'年'MM'月'dd'日'HH'時'mm'分'ss'秒'");
}
body += "■"+item+"\n";
body += value + "\n\n";
if ( item === name ) {
body = value+" 様\n\n"+body;
}
if ( item === mail ) {
address = value;
}
}
body += body2;
var token = ScriptApp.getOAuthToken();
var pdf = UrlFetchApp.fetch("https://docs.google.com/spreadsheets/d/OOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOO/export?exportFormat=pdf&format=pdf&size=A4&portrait=true&fitw=true&sheetnames=false&printtitle=false&pagenumbers=false&gridlines=false&fzr=false&gid=00000000000", {headers: {'Authorization': 'Bearer ' + token}}).getBlob().setName('請求書');
GmailApp.sendEmail(
address,
title,
body,
{
attachments: [pdf],
name: 'Automatic Emailer Script'
}
);
}
There is no error. It's just that the invoice attached is from one previous customer.
Thank you to the people who have answered my question. Special thanks to Tanaike who have suggested a workaround where I was able to use as a starter to GAS.
As I used Utilities.sleep(5000), whenever someone submits google form, the invoice produced (PDF format) is updated to the newest info. Since the program I created isn't aimed for very heavy processes, it may be the reason why it worked perfectly fine.
If SpreasheetApp.flush() doesn't seem to be working then you should certainly move to the onFormSubmit - Installable Trigger.
Triggers - Form Submit
This way you can process the exact values from the form and use the same function you are using now. Instead of fetching the last row values, you can fetch the values from the form submission using this.
var name = e.namedValues['Name'][0]; var email = e.namedValues['Email'][0];
I have a set of scripts that I'm using that interact with each other. I use a client, user event and suitelet script to create a button that, when pressed, opens a popup with a list of items filtered by vendor.
It works fine when I'm in edit however when I use it while creating a record problems arise. Since the record to be created has no vendor or id I can't retrieve an item by vendor. What I'm trying to do is to have the Suitelet retrieve the info from the vendor field that is entered prior to it being saved. Therefore I can filter all the items by vendor and add the necessary items in one go. Is this possible? Am I able to access the info before it is submitted.
Below are the Client and Suitelet. The User Event is just a call to the suitelet so for the sake of brevity I left it out.
Client Script
function addItemButtonCallback(data){
nlapiSelectNewLineItem('item');
nlapiSetCurrentLineItemValue('item', 'item', data);
nlapiCommitLineItem('inventoryitem');
}
function addItemButton() {
var id = nlapiGetFieldValue('id');
if (id != "") {
var url = nlapiResolveURL('SUITELET', 'customscript_val', 'customdeploy1') + '&poId='+id;
window.open(url, '_blank', 'width=500,height=500');
}
}
Suitelet
function suitelet(request, response){
if(request.getMethod() == 'GET') {
var form = nlapiCreateForm('Add Item');
form.addSubmitButton('Submit');
var itemfield = form.addField('custpage_val', 'select', 'Item');
var id = request.getParameter('id');
var rec = nlapiLoadRecord('purchaseorder', id);
var vend = rec.getFieldValue('entity');
var search = nlapiSearchRecord(...search parameters...);
for (result in search){
if (search[result].getValue('vendor') == vend){
itemfield.addSelectOption(search[result].id, nlapiLookupField('inventoryitem', search[result].id, 'itemid'));
}
}
response.writePage(form);
} else {
var data = request.getParameter('custpage_item');
response.write('<html><body><script>window.opener.addItemButtonCallback("'+data+'"); window.close();</script></body></html>');
}
}
Use nlapiGetFieldValue('entity') on the clientscript and pass it to the Suitelet using a query parameter just like you are doing with poId (if you do this you might not even need poId after all + no need to load the record on the suitelet).
Also, you might want to optimize your code by running one search passing an array of itemids instead of calling nlapiLookupField for each item.
You might need to modify your beforeLoad so the entity is inserted dynamically when the button is pressed (I cant remember if clientscript button does this) . Something like this:
var suiteletURL = nlapiResolveURL('SUITELET', 'customscript_val', 'customdeploy1');
var script = "var entity = nlapiGetFieldValue('entity'); var url = '" + suiteletURL + "'&entityId=' + entity;window.open(url, '_blank', 'width=500,height=500')";
var button = form.addButton('custpage_addItemButton', 'Add Item', script);
Attempting to create a script that will pull information from an API requested XML document and put it into a 2D array.
Upon making the Get request
https://api.example.com/v1.svc/users?apikey=MY-KEY&source=MY-APP&limit=1000
An XML is produced for each user looking like
<User>
<Id>Rdh9Rsi3k4U1</Id>
<UserName>firstlast#email.com</UserName>
<FirstName>First</FirstName>
<LastName>Last</LastName>
<Active>true</Active>
<Email>firstlast#email.com</Email>
<AccessLevel>Learner</AccessLevel>
</User>
Each user has a similar looking output stacked on top of each other. How could this be scrubbed into an array? Example, the first array would have 7 "columns" with all shown information with each user having a row.
b
So I figured it out for anyone looking for an answer to this type of question in the future. Basically, I found out that the API I was trying to reach (not actually "citrowske.com" as shown in the example) did not allow for CORS or jsonp which left me with the only option of using a Proxy.
Shown is an example of code similar to what I ended up using (below), along with the test XML file shown here
A basic explanation of how this works, it uses the proxy to get the XML file and stores it as "xml" found as "function(xml)". Then the XML doc is searched and each section that starts with "User" gets the "FirstName" and "LastName" data pulled from it and appended to dropdown in the HTML section named "yourdropdownbox".
$.ajaxPrefilter( function (options) {
if (options.crossDomain && jQuery.support.cors) {
var http = (window.location.protocol === 'http:' ? 'http:' : 'https:');
options.url = http + '//cors-anywhere.herokuapp.com/' + options.url;
//options.url = "http://cors.corsproxy.io/url=" + options.url;
}
});
$.get(
'http://citrowske.com/xml.xml',
function (xml) {
//console.log("> ", xml);
//$("#viewer").html(xml);
////////////////////////////////////
var select = $('#yourdropdownbox');
select.append('<option value="">Select a User</option>');
$(xml).find('User').each(function(){
var FirstNames = $(this).find('FirstName').text();
var LastNames = $(this).find('LastName').text();
select.append("<option value='"+ FirstNames +"'>"+FirstNames+" "+LastNames+"</option>");
});
}
////////////////////////////////////
);
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<select id="yourdropdownbox">
</select>
As a note, Proxy's are not known for being extremely secure, so watch out what you use this for.
Also, if I wanted to turn the data into an array instead of appending it each time I could have added
var firstnamesarray = ["0"];
var lastnamesarry = ["0"];
var i = 0;
Above the top row of forward-slashes and then replaced:
var FirstNames = $(this).find('FirstName').text();
var LastNames = $(this).find('LastName').text();
with
firstnamesarry[i] = $(this).find('FirstName').text();
lastnamesarry[i] = $(this).find('LastName').text();
i = i+1;
and replaced the "select.append" First & Last Names with
firstnamearry[i] & lastnamearry[i]
To view a working example, check out the jsfiddle here
I have created a Google form that is linked to a Google spreadsheet containing two sheets. I have also created a function in Google Scripts, called "handleFormSubmission", that when triggered (on submission of the linked form):
creates a variable containing the values of this submission from sheet one: var s0Row = s0.getRange("A"+(s0Last)+":J"+(s0Last)).getValues();
then, if a matching ID condition is met on both sheets, sets those values from sheet one into the appropriate range on sheet two: s1Row.setValues(s0Row);
There's probably a better way to do this, but for now the function works fine when run from Google Scripts and the form is returning submissions to sheet one.
The problem I'm having is getting this function to trigger when the linked form has been submitted. I've attempted to set this trigger up as you'll see in the screen shot below.
Code
function handleFormSubmission() {
var ss = SpreadsheetApp.openById("1FmArzo50IV2Wmykgsa89l_EARjzkiyeFDoPaCjGyBZM");
SpreadsheetApp.setActiveSpreadsheet(ss);
var sheet = SpreadsheetApp.getActive();
var s0 = sheet.getSheets()[0];
var s0Last = s0.getLastRow();
var s1 = sheet.getSheets()[1];
var s1Last = s1.getLastRow();
var s0Bid = s0.getRange(s0Last, 10).getValue();
var s0Row = s0.getRange("A"+(s0Last)+":J"+(s0Last)).getValues();
for (var i = 2; i < s1Last + 1; i++) {
var s1Bid = s1.getRange(i, 10).getValue();
var s1First = s1.getRange(i, 2).getValue();
var s1LastName = s1.getRange(i, 3).getValue();
var s1Row = s1.getRange("A"+(i)+":J"+(i));
if (s0Bid === s1Bid) {
Logger.log(i + " " + s1First + s1LastName);
Logger.log("s0: " + s0Bid);
Logger.log("s1: " + s1Bid);
Logger.log("Match!");
s1Row.setValues(s0Row);
Logger.log("----------------------");
break;
} else {
Logger.log(i + " " + s1First + s1LastName);
Logger.log("s0: " + s0Bid);
Logger.log("s1: " + s1Bid);
Logger.log("Nope...");
Logger.log("----------------------");
}
};
};`
Current Project's Triggers
It's definitely an event on the spreadsheet that you're intercepting, although that may seem counter-intuitive.
I had the same problem & solved it by deleting the trigger, creating a new version of the script, then recreating the trigger. Don't know why it works -- perhaps a GAppsScript expert could explain it to us.
Also, why not get your form submission values out of the event object? So, instead of hunting down the last row of sheet[0] (which could, in an extreme case, not be the submission you're looking for, but the next one), you can access the field you want from the event object using either of:
e.values (an array of the form values in the order they appear in the spreadsheet)
e.namedValues (a dictionary/hash of the form values)
I think the event should be "From form" not "From spreadsheet". That is because you are working on script editor opened from the spreadsheet. It populates when you open the script editor from the form and write the function in that editor. Hope that helps!
I am trying to build a very simple tool for use at my work. I work for eBay and currently the tools available are cumbersome for the task. We are asked to compare text and images to check that sellers aren't stealing each others content. I am using the eBay Trading API and the sample HTML/CSS/Javascript code given when the developer account was created. Ultimately what I hope to achieve is a simple page that displays two items' photo and description next to each other. However, right now I am simply trying to edit the sample code given to display the start date of the auction.
My question is this: I am trying add a variable who's value is determined by a response from the API. some of these are provided in the sample however, when I add my own var starttime = items.listingInfo.startTime to the function and add the variable to the HTML table none of the data displays including those that displayed prior to my addition. Unfortunately I don't have more than a rudimentary understanding of javascript and so am unsure if I am even properly phrasing this question, let alone getting the syntax of my addition correct. What am I doing wrong?
below is the sample text with my addition of one declared variable (starttime) and one addition to the HTML table
<html>
<head>
<title>eBay Search Results</title>
<style type="text/css">body { font-family: arial,sans-serif;} </style>
</head>
<body>
<h1>eBay Search Results</h1>
<div id="results"></div>
<script>
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 viewitem = item.viewItemURL;
var starttime = items.listingInfo.startTime;
if (null != title && null != viewitem)
{
html.push('<tr><td>' + '<img src="' + pic + '" border="0">' + '</td>' +
'<td>' + title + '' + starttime + '</td></tr>');
}
}
html.push('</tbody></table>');
document.getElementById("results").innerHTML = html.join("");
}
</script>
<!--
Use the value of your appid for the appid parameter below.
-->
<script src=http://svcs.ebay.com/services/search/FindingService/v1?SECURITY-APPNAME=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx&OPERATION-NAME=findItemsByKeywords&SERVICE-VERSION=1.0.0&RESPONSE-DATA-FORMAT=JSON&callback=_cb_findItemsByKeywords&REST-PAYLOAD&keywords=iphone%203g&paginationInput.entriesPerPage=3>
</script>
</body>
</html>"
If you believe listingInfo is an property of individual items, and that it is an object that has the property startTime, then the proper syntax is:
var item = items[i];
var title = item.title;
var viewitem = item.viewItemURL;
var starttime = item.listingInfo.startTime;
You are currently referencing items which is the array of items, not an individual item.
Update
I looked into this via the URL you put in the comments. The solution to this particular problem is this:
var starttime = item.listingInfo[0].startTime;
I hope that helps. Please review the FAQ; Imho this question falls outside the scope of this site (the question is really quite narrow, and not likely to help anyone else). I recommend Mozilla Developer Network as a source for learning more about JavaScript.