Dynamic parent/child in a table - javascript

How can I make parent("td").prevAll("td") to be dynamic?
$("body").on("click",".edit-item",function(){
var id = $(this).parent("td").data('id');
var name = $(this).parent("td").prevAll("td").eq(9).text();
var email = $(this).parent("td").prevAll("td").eq(8).text();
var phone = $(this).parent("td").prevAll("td").eq(7).text();
var CNP = $(this).parent("td").prevAll("td").eq(6).text();
var birthday = $(this).parent("td").prevAll("td").eq(5).text();
var date = $(this).parent("td").prevAll("td").eq(4).text();
var speciality_id = $(this).parent("td").prevAll("td").eq(3).text();
var doctor_id = $(this).parent("td").prevAll("td").eq(2).text();
var location_id = $(this).parent("td").prevAll("td").eq(1).text();
var message = $(this).parent("td").prevAll("td").eq(0).text();
$("#edit-item").find("input[name='name']").val(name);
$("#edit-item").find("input[name='email']").val(email);
$("#edit-item").find("input[name='phone']").val(phone);
$("#edit-item").find("input[name='CNP']").val(CNP);
$("#edit-item").find("input[name='birthday']").val(birthday);
$("#edit-item").find("input[name='date']").val(date);
$("#edit-item").find("select[name='speciality_id']").val(speciality_id);
$("#edit-item").find("select[name='doctor_id']").val(doctor_id);
$("#edit-item").find("select[name='location_id']").val(location_id);
$("#edit-item").find("textarea[name='message']").val(message);
$("#edit-item").find("form").attr("action",url + '/' + id);
});

Related

Set values from different sheets to another sheet

In summary, I'm trying to simplify this function that load values from two different sheets to another sheet.
All the values are stored in rows in two sheets (DBClienti and DataBkp), all these rows have a reference cell with a unique ID. I select an ID from DBClienti and the function find the relative row number, corresponding to the data to load in the last sheet (Quota).
I'm setting this data using all those vars, but of course there is a better (and right) way that I don't know.
function loadDataBkp() {
const ss = SpreadsheetApp.getActiveSpreadsheet();
const sheetQuota = ss.getSheetByName('Quota');
const sheetDBClienti = ss.getSheetByName("DBClienti");
const sheetDataBkp = ss.getSheetByName("DataBkp");
//Reset Inputs
resetQuota();
//Select the ID DOC
var selectedIDDoc = sheetDBClienti.getActiveCell();
var selectedIDDocVal = selectedIDDoc.getValue();
//Find row of ID DOC in DBClienti
var rowDBClienti;
const dataDBClienti = sheetDBClienti.getDataRange().getValues();
for(var i = 0; i<dataDBClienti.length;i++){
if(dataDBClienti[i][9] == selectedIDDocVal){
rowDBClienti = i+1;
}
}
//Set values in Quota - list
var valI4 = sheetDBClienti.getRange(rowDBClienti,1).getValue();
var valI5 = sheetDBClienti.getRange(rowDBClienti,2).getValue();
var valI6 = sheetDBClienti.getRange(rowDBClienti,3).getValue();
var valI7 = sheetDBClienti.getRange(rowDBClienti,4).getValue();
var valI8 = sheetDBClienti.getRange(rowDBClienti,5).getValue();
var valI9 = sheetDBClienti.getRange(rowDBClienti,6).getValue();
var valI10 = sheetDBClienti.getRange(rowDBClienti,7).getValue();
var valI11 = sheetDBClienti.getRange(rowDBClienti,8).getValue();
sheetQuota.getRange('I4').setValue(valI4);
sheetQuota.getRange('I5').setValue(valI5);
sheetQuota.getRange('I6').setValue(valI6);
sheetQuota.getRange('I7').setValue(valI7);
sheetQuota.getRange('I8').setValue(valI8);
sheetQuota.getRange('I9').setValue(valI9);
sheetQuota.getRange('I10').setValue(valI10);
sheetQuota.getRange('I11').setValue(valI11);
//Find row of ID DOC in DataBkp
var rowDataBkp;
const dataDataBkp = sheetDataBkp.getDataRange().getValues();
for(var i = 0; i<dataDataBkp.length;i++){
if(dataDataBkp[i][0] == selectedIDDocVal){
rowDataBkp = i+1;
}
}
//Set values in Quota - sections
var valC2 = sheetDataBkp.getRange(rowDataBkp,2).getValue();
var valC4 = sheetDataBkp.getRange(rowDataBkp,3).getValue();
var valC5 = sheetDataBkp.getRange(rowDataBkp,4).getValue();
var valC6 = sheetDataBkp.getRange(rowDataBkp,5).getValue();
var valC7 = sheetDataBkp.getRange(rowDataBkp,6).getValue();
var valC8 = sheetDataBkp.getRange(rowDataBkp,7).getValue();
var valC9 = sheetDataBkp.getRange(rowDataBkp,8).getValue();
var valC10 = sheetDataBkp.getRange(rowDataBkp,9).getValue();
var valC11 = sheetDataBkp.getRange(rowDataBkp,10).getValue();
var valC12 = sheetDataBkp.getRange(rowDataBkp,11).getValue();
var valF4 = sheetDataBkp.getRange(rowDataBkp,12).getValue();
var valF5 = sheetDataBkp.getRange(rowDataBkp,13).getValue();
var valF8 = sheetDataBkp.getRange(rowDataBkp,14).getValue();
var valF9 = sheetDataBkp.getRange(rowDataBkp,15).getValue();
var valF12 = sheetDataBkp.getRange(rowDataBkp,16).getValue();
var valF13 = sheetDataBkp.getRange(rowDataBkp,17).getValue();
var valF25 = sheetDataBkp.getRange(rowDataBkp,18).getValue();
var valF26 = sheetDataBkp.getRange(rowDataBkp,19).getValue();
var valF27 = sheetDataBkp.getRange(rowDataBkp,20).getValue();
var valI14 = sheetDataBkp.getRange(rowDataBkp,21).getValue();
sheetQuota.getRange('C2').setValue(valC2);
sheetQuota.getRange('C4').setValue(valC4);
sheetQuota.getRange('C5').setValue(valC5);
sheetQuota.getRange('C6').setValue(valC6);
sheetQuota.getRange('C7').setValue(valC7);
sheetQuota.getRange('C8').setValue(valC8);
sheetQuota.getRange('C9').setValue(valC9);
sheetQuota.getRange('C10').setValue(valC10);
sheetQuota.getRange('C11').setValue(valC11);
sheetQuota.getRange('C12').setValue(valC12);
sheetQuota.getRange('F4').setValue(valF4);
sheetQuota.getRange('F5').setValue(valF5);
sheetQuota.getRange('F8').setValue(valF8);
sheetQuota.getRange('F9').setValue(valF9);
sheetQuota.getRange('F12').setValue(valF12);
sheetQuota.getRange('F13').setValue(valF13);
sheetQuota.getRange('F25').setValue(valF25);
sheetQuota.getRange('F26').setValue(valF26);
sheetQuota.getRange('F27').setValue(valF27);
sheetQuota.getRange('I14').setValue(valI14);
}
Try it this way:
function loadDataBkp() {
const ss = SpreadsheetApp.getActiveSpreadsheet();
const sh1 = ss.getSheetByName('Quota');
const sh2 = ss.getSheetByName("DBClienti");
const sh3 = ss.getSheetByName("DataBkp");
resetQuota();
var v2 = sh2.getActiveCell().getValue();
var row1;
sh2.getDataRange().getValues().forEach((r,i) => { if (r[9] == v2) { row1 = i + 1; } })
sh1.getRange(4, 9, 8).setValues(sh2.getRange(row1, 1, 1, 8).getValues().flat().map(v => [v]))
var row2;
const vs3 = sh3.getDataRange().getValues().forEach((r, i) => { if (r[0] == v2) { row2 = i + 1 } })
let xvs = sh3.getRange(row2, 2, 1, 20).getValues().flat();
['C2', 'C4', 'C5', 'C6', 'C7', 'C8', 'C9', 'C10', 'C11', 'C12', 'F4', 'F5', 'F8', 'F9', 'F12', 'F13', 'F25', 'F26', 'F27', 'I14'].forEach((s, i) => { sh1.getRange(s).setValue(xvs[i]) });
}

Undefined global variables in function

I'm trying to use javascript to perform calculations on a button click because I don't want the page to refresh when this button is clicked. I wrote a script below:
var name = document.getElementById('recipeName').value;
var lvl = document.getElementById('recipeLvl').value;
var e = document.getElementById("qualitySelect");
var quality = e.options[e.selectedIndex].value;
e = document.getElementById("classSelect");
var craft = e.options[e.selectedIndex].value;
var mat1 = document.getElementById('material1Name').value;
var mat1Qty = document.getElementById('material1Qty').value;
var mat1NQ = document.getElementById('material1NQ').value;
var mat1NQprice = document.getElementById('material1NQprice').value;
var mat1HQ = document.getElementById('material1HQ').value;
var mat1HQprice = document.getElementById('material1HQprice').value;
var mat2 = document.getElementById('material2Name').value;
var mat2Qty = document.getElementById('material2Qty').value;
var mat2NQ = document.getElementById('material2NQ').value;
var mat2NQprice = document.getElementById('material2NQprice').value;
var mat2HQ = document.getElementById('material2HQ').value;
var mat2HQprice = document.getElementById('material2HQprice').value;
var mat3 = document.getElementById('material3Name').value;
var mat3Qty = document.getElementById('material3Qty').value;
var mat3NQ = document.getElementById('material3NQ').value;
var mat3NQprice = document.getElementById('material3NQprice').value;
var mat3HQ = document.getElementById('material3HQ').value;
var mat3HQprice = document.getElementById('material3HQprice').value;
var mat4 = document.getElementById('material4Name').value;
var mat4Qty = document.getElementById('material4Qty').value;
var mat4NQ = document.getElementById('material4NQ').value;
var mat4NQprice = document.getElementById('material4NQprice').value;
var mat4HQ = document.getElementById('material4HQ').value;
var mat4HQprice = document.getElementById('material4HQprice').value;
var mat5 = document.getElementById('material5Name').value;
var mat5Qty = document.getElementById('material5Qty').value;
var mat5NQ = document.getElementById('material5NQ').value;
var mat5NQprice = document.getElementById('material5NQprice').value;
var mat5HQ = document.getElementById('material5HQ').value;
var mat5HQprice = document.getElementById('material5HQprice').value;
var mat6 = document.getElementById('material6Name').value;
var mat6Qty = document.getElementById('material6Qty').value;
var mat6NQ = document.getElementById('material6NQ').value;
var mat6NQprice = document.getElementById('material6NQprice').value;
var mat6HQ = document.getElementById('material6HQ').value;
var mat6HQprice = document.getElementById('material6HQprice').value;
e = document.getElementById("catalyst1");
var crystal1 = e.options[e.selectedIndex].value;
e = document.getElementById('element1');
var element1 = e.options[e.selectedIndex].value;
var crystal1Qty = document.getElementById('crystalQty1').value;
var crystal1Price = document.getElementById('crystalPrice1').value;
e = document.getElementById("catalyst2");
var crystal2 = e.options[e.selectedIndex].value;
e = document.getElementById('element2');
var element2 = e.options[e.selectedIndex].value;
var crystal2Qty = document.getElementById('crystalQty2').value;
var crystal2Price = document.getElementById('crystalPrice2').value;
var notes = document.getElementById('notes').value;
var marketPrice = document.getElementById('marketPrice').value;
function calculate() {
var mat1Cost = (mat1NQ * mat1NQprice) + (mat1HQ * mat1HQprice);
var mat2Cost = (mat2NQ * mat2NQprice) + (mat2HQ * mat2HQprice);
var mat3Cost = (mat3NQ * mat3NQprice) + (mat3HQ * mat3HQprice);
var mat4Cost = (mat4NQ * mat4NQprice) + (mat4HQ * mat4HQprice);
var mat5Cost = (mat5NQ * mat5NQprice) + (mat5HQ * mat5HQprice);
var mat6Cost = (mat6NQ * mat6NQprice) + (mat6HQ * mat6HQprice);
var crystal1Cost = (crystal1Qty * crystal1Price);
var crystal2Cost = (crystal2Qty * crystal2Price);
var total = mat1Cost +
mat1Cost +
mat1Cost +
mat1Cost +
mat1Cost +
mat1Cost +
crystal1Cost +
crystal2Cost;
document.getElementById('totalCost').value = mat1Cost;
return false;
}
I'm new to javascript, and thought declaring the variables right after would make them accessible to any function that I would need to use them in, but they are undefined in the calculate function. If I declare them in calculate() it's fine, so is this a scope problem?
Thanks in advance for any help!
The problem is you're grabbing the elements values before you've assigned anything to them. You're getting a copy, not a reference.
var initialValue = document.getElementById('text').value;
function clickHandler() {
// Notice how I have to grab the value again when I want an updated value
var updatedValue = document.getElementById('text').value;
console.log('Initial:', initialValue);
console.log('Updated:', updatedValue);
}
<input id="text" />
<button onclick="clickHandler()">Click Me</button>
#epascarello has commented the real answer, there is no much science there, this is javascript, therefore is a script language, so as soon as this file is loaded, those variables are filled with the initial data of each field, so, if you want to get the value at the point you press calculate(), you should get your variables.

Struggling with repeating code with JavaScript and DOM

For an assignment i need to create a website which outputs mobile phone contracts based on the users preferences. I am currently stuck at the DOM part of the assignment.
I would like to output the results into a list, which i have managed to do, though i'm sure there's a better way to do it using less code.
This is what i have so far: https://jsfiddle.net/fn2ewtck/
The code i am trying to improve is this:
function search() {
var userBrandCtrl = document.getElementById("userBrand");
var userBrand = userBrandCtrl.value;
var userModelCtrl = document.getElementById("userModel");
var userModel = userModelCtrl.value;
var userNetworkCtrl = document.getElementById("userNetwork");
var userNetwork = userNetworkCtrl.value;
for (var i = 0; cont.length; i++) {
if (userBrand === cont[i].brand && userModel === cont[i].model && userNetwork === cont[i].network) {
var body = document.body;
var ulCont = document.createElement("ul");
var liBrand = document.createElement("li");
var liModel = document.createElement("li");
var liNetwork = document.createElement("li");
var liMins = document.createElement("li");
var liTexts = document.createElement("li");
var liData = document.createElement("li");
var liUpfront = document.createElement("li");
var liMonthly = document.createElement("li");
var liLength = document.createElement("li");
var textBrand = document.createTextNode("Brand: " + cont[i].brand);
var textModel = document.createTextNode("Model: " + cont[i].model);
var textNetwork = document.createTextNode("Network " + cont[i].network);
var textMins = document.createTextNode("Mins: " + cont[i].mins);
var textTexts = document.createTextNode("Texts: " + cont[i].texts);
var textData = document.createTextNode("Data: " + cont[i].data);
var textUpfront = document.createTextNode("Upfront: " + cont[i].upfront);
var textMonthly = document.createTextNode("Monthly: " + cont[i].monthly);
var textLength = document.createTextNode("Length: " + cont[i].length);
liBrand.appendChild(textBrand);
liModel.appendChild(textModel);
liNetwork.appendChild(textNetwork);
liMins.appendChild(textMins);
liTexts.appendChild(textTexts);
liData.appendChild(textData);
liUpfront.appendChild(textUpfront);
liMonthly.appendChild(textMonthly);
liLength.appendChild(textLength);
ulCont.appendChild(liBrand);
ulCont.appendChild(liModel);
ulCont.appendChild(liNetwork);
ulCont.appendChild(liMins);
ulCont.appendChild(liTexts);
ulCont.appendChild(liData);
ulCont.appendChild(liUpfront);
ulCont.appendChild(liMonthly);
ulCont.appendChild(liLength);
body.appendChild(ulCont);
}
}
};
How could i do this better?
Thanks.
You could create an array of the properties you want to display from the object and loop over them like this:
var arr = ['brand', 'model', 'network', 'mins']
for (i = 0; i < arr.length; i++) {
//Upercase first letter
var label = arr[i].charAt(0).toUpperCase() + arr[i].slice(1);
//create html elements
var li = document.createElement("li"),
text = document.createTextNode(label + ": " + cont[i][arr[i]]);
li.appendChild(text);
ulCont.appendChild(li);
}
//append to body after loop
body.appendChild(ulCont);
You should look at Backbone and Dust. They'll help you templatize the HTML you're trying to write.

Reading and writing values from form doesn't work

I have a code sample where I want to read some data from input fields and write that data to a different div.
In first section the code works properly, but in 2nd section the value is not shown. I used the alert function to check that wether value is received or not. The value is received but not shown.
What is wrong with my code? (below)
function preview() {
$(".preview_block").fadeIn(1000);
$("body").css("overflow","hidden");
$(".preview_block").css("overflow","auto");
/*======================Value fetch for personal details=======================*/
var fastname1 = document.forms["myform"]["fastname"].value;
if(fastname1==""){fastname1="---null---"}
var lastname1 = document.forms["myform"]["lastname"].value;
if(lastname1==""){lastname1="---null---"}
var sex1 = document.forms["myform"]["radio"].value;
if(sex1==""){sex1="---null---"}
var clgid1 = document.forms["myform"]["clgid"].value;
if(clgid1==""){clgid1="---null---"}
var dob1 = document.forms["myform"]["dob"].value;
if(dob1==""){dob1="---null---"}
var fname1 = document.forms["myform"]["fname"].value;
if(fname1==""){fname1="---null---"}
var mname1 = document.forms["myform"]["mname"].value;
if(mname1==""){mname1="---null---"}
var gname1 = document.forms["myform"]["gname"].value;
if(gname1==""){gname1="---null---"}
var mobno1 = document.forms["myform"]["mobno"].value;
if(mobno1==""){mobno1="---null---"}
var pmobno1 = document.forms["myform"]["pmobno"].value;
if(pmobno1==""){pmobno1="---null---"}
var mail1 = document.forms["myform"]["mail"].value;
if(mail1==""){mail1="---null---"}
var addr11 = document.forms["myform"]["addr1"].value;
if(addr11==""){addr11="---null---"}
var addr21 = document.forms["myform"]["addr2"].value;
if(addr21==""){addr21="---null---"}
var city1 = document.forms["myform"]["city"].value;
if(city1==""){city1="---null---"}
var state1 = document.forms["myform"]["state"].value;
if(state1==""){state1="---null---"}
var pcode1 = document.forms["myform"]["pcode"].value;
if(pcode1==""){pcode1="---null---"}
var ps1 = document.forms["myform"]["ps"].value;
if(ps1==""){ps1="---null---"}
var po1 = document.forms["myform"]["po"].value;
if(po1==""){po1="---null---"}
var country1 = document.forms["myform"]["country"].value;
if(country1==""){country1="---null---"}
document.getElementById("p1").innerHTML = fastname1;
document.getElementById("p2").innerHTML = lastname1;
document.getElementById("p3").innerHTML = sex1;
document.getElementById("p4").innerHTML = clgid1;
document.getElementById("p5").innerHTML = dob1;
document.getElementById("p6").innerHTML = fname1;
document.getElementById("p7").innerHTML = mname1;
document.getElementById("p8").innerHTML = gname1;
document.getElementById("p9").innerHTML = mobno1;
document.getElementById("p10").innerHTML = pmobno1;
document.getElementById("p11").innerHTML = mail1;
document.getElementById("p12").innerHTML = addr11;
document.getElementById("p13").innerHTML = addr21;
document.getElementById("p14").innerHTML = city1;
document.getElementById("p15").innerHTML = state1;
document.getElementById("p16").innerHTML = pcode1;
document.getElementById("p17").innerHTML = ps1;
document.getElementById("p18").innerHTML = po1;
document.getElementById("p19").innerHTML = country1;
/*======================Value fetch for XII standered details=======================*/
var qualification1 = $('#qualification option:selected').html();
if(qualification1==""){qualification1="---null---"}
var q1_board1 = $('#q1_board option:selected').html();
if(q1_board1==""){q1_board1="---null---"}
var clg_nm1 = document.forms["myform"]["clg_nm"].value;
if(session1==""){session1="---null---"}
var regno1 = document.forms["myform"]["regno"].value;
if(regno1==""){regno1="---null---"}
var yr_reg1 = document.forms["myform"]["yr_reg"].value;
if(yr_reg1==""){yr_reg1="---null---"}
var rollno1 = document.forms["myform"]["rollno"].value;
if(rollno1==""){rollno1="---null---"}
document.getElementById("q1").innerHTML = qualification1;
document.getElementById("q2").innerHTML = q1_board1;
document.getElementById("q3").innerHTML = clg_nm1;
document.getElementById("q4").innerHTML = regno1;
document.getElementById("q5").innerHTML = yr_reg1;
document.getElementById("q6").innerHTML = rollno1;
}

Google App Script Spreadsheet

here is the code
function makeaCVdoc(){
var sheet = SpreadsheetApp.getActiveSpreadsheet();
var startRow = 2;
var numRows = sheet.getLastRow() -1;
var EMAIL_SENT = "EMAIL_SENT";
var subject = "Here is your CV";
//var dataRange = sheet.getRange(2,2,numRows,50);
var data = dataRange.getValues();
for(var i = 0; i < data.length; ++i)
{
var row = data[i];
var firstname = row[1];
var secondname = row[2];
var thiredname = row[3];
var address = row[4]
var email_address = row[5];
var homenumber = row[6];
var mobilenumber= row[7];
var objective = row[8];
var language = row[9];
var educationwithdegree = row[10];
var computerskill = row[11];
var TrainingCourse = row[12];
var Hobbies = row[13];
var DOB = row[14];
var nationality = row[15];
var MaritalStatus = row[16]
var emailSent = row[17];
var CVdoc = DocumentApp.create(firstname+' '+secondname+' '+thiredname);
var par1 = CVdoc.getBody().appendParagraph(firstname+' '+secondname+' '+thiredname);
par1.setHeading(DocumentApp.ParagraphHeading.TITLE);
var par2 = CVdoc.getBody().appendParagraph("Address: ");
par2.setHeading(DocumentApp.ParagraphHeading.HEADING2);
CVdoc.getBody().appendParagraph(address);
var par3 = CVdoc.getBody().appendParagraph("Email Address: ");
par3.setHeading(DocumentApp.ParagraphHeading.HEADING2);
CVdoc.getBody().appendParagraph(email_address);
var par4 = CVdoc.getBody().appendParagraph("Home Number: ");
par4.setHeading(DocumentApp.ParagraphHeading.HEADING2);
CVdoc.getBody().appendParagraph(homenumber);
var par5 = CVdoc.getBody().appendParagraph("Mobile Number: ");
par5.setHeading(DocumentApp.ParagraphHeading.HEADING2);
CVdoc.getBody().appendParagraph(mobilenumber);
var par6 = CVdoc.getBody().appendParagraph("Objective: ");
par6.setHeading(DocumentApp.ParagraphHeading.HEADING2);
CVdoc.getBody().appendParagraph(objective);
var par7 = CVdoc.getBody().appendParagraph("Spoken Languages: ");
par7.setHeading(DocumentApp.ParagraphHeading.HEADING2);
CVdoc.getBody().appendParagraph(language);
var par8 = CVdoc.getBody().appendParagraph("Education and Degree: ");
par8.setHeading(DocumentApp.ParagraphHeading.HEADING2);
CVdoc.getBody().appendParagraph(educationwithdegree);
var par9 = CVdoc.getBody().appendParagraph("Computer Skills: ");
par9.setHeading(DocumentApp.ParagraphHeading.HEADING2);
CVdoc.getBody().appendParagraph(computerskill);
var par10 = CVdoc.getBody().appendParagraph("Training Courses: ");
par10.setHeading(DocumentApp.ParagraphHeading.HEADING2);
CVdoc.getBody().appendParagraph(TrainingCourse);
var par11 = CVdoc.getBody().appendParagraph("Hobbies: ");
par11.setHeading(DocumentApp.ParagraphHeading.HEADING2);
CVdoc.getBody().appendParagraph(Hobbies);
var par12 = CVdoc.getBody().appendParagraph("Nationality: ");
par12.setHeading(DocumentApp.ParagraphHeading.HEADING2);
CVdoc.getBody().appendParagraph(nationality);
var par13 = CVdoc.getBody().appendParagraph("Date Of Birth: ");
par13.setHeading(DocumentApp.ParagraphHeading.HEADING2);
CVdoc.getBody().appendParagraph(DOB);
var par14 = CVdoc.getBody().appendParagraph("Marital Status: ");
par14.setHeading(DocumentApp.ParagraphHeading.HEADING2);
CVdoc.getBody().appendParagraph(MaritalStatus);
var url = CVdoc.getUrl();
var body = 'Link to your doc: ' + url +'Thank you for using our Tech';
if(emailSent != EMAIL_SENT)
{
//GmailApp.sendEmail(email_address, subject, body);
//sheet.getRange(2,17).setValue(EMAIL_SENT);
SpreadsheetApp.flush();
}
}
}
it's basically a form that i want to use to get all the information that it's needed in order to make a CV and after the user enter all the information and submit the form it's stored at a spreadsheet than i have this code inside this spreadsheet but something wrong with the comment lines and i still don't know why
i get something wrong with the getRange() command
which lead to another code error at the GmailApp command
right now i made them as comments
but no matter what i do i don't know what's wrong
so please could anyone help me
some said that they needed more information about the error
like i said the error is at the commented lines
var dataRange = sheet.getRange(2,2,numRows,50);
GmailApp.sendEmail(email_address, subject, body);
sheet.getRange(2,17).setValue(EMAIL_SENT);
it basically tell me error at line whatever the line is
and write the line to me as a function
what i mean is getRange(number,number,number,number);
and that's all what i get nothing more nothing less
this is the code after i changed it
function makeaCVdoc()
{
var sheet = SpreadsheetApp.getActiveSpreadsheet();
var startRow = 2;
var numRows = sheet.getLastRow() -1;
var EMAIL_SENT = "EMAIL_SENT";
var subject = "Here is your CV";
var dataRange = sheet.getRange("B2:R2");
var data = dataRange.getValues();
for(var i = 0; i < data.length; ++i)
{
var row = data[i];
var firstname = row[0];
var secondname = row[1];
var thiredname = row[2];
var address = row[3]
var email_address = row[4];
var homenumber = row[5];
var mobilenumber= row[6];
var objective = row[7];
var language = row[8];
var educationwithdegree = row[9];
var computerskill = row[10];
var TrainingCourse = row[11];
var Hobbies = row[12];
var DOB = row[13];
var nationality = row[14];
var MaritalStatus = row[15]
var emailSent = row[16];
var CVdoc = DocumentApp.create(firstname+' '+secondname+' '+thiredname);
var par1 = CVdoc.getBody().appendParagraph(firstname+' '+secondname+' '+thiredname);
par1.setHeading(DocumentApp.ParagraphHeading.TITLE);
var par2 = CVdoc.getBody().appendParagraph("Address: ");
par2.setHeading(DocumentApp.ParagraphHeading.HEADING2);
CVdoc.getBody().appendParagraph(address);
var par3 = CVdoc.getBody().appendParagraph("Email Address: ");
par3.setHeading(DocumentApp.ParagraphHeading.HEADING2);
CVdoc.getBody().appendParagraph(email_address);
var par4 = CVdoc.getBody().appendParagraph("Home Number: ");
par4.setHeading(DocumentApp.ParagraphHeading.HEADING2);
CVdoc.getBody().appendParagraph(homenumber);
var par5 = CVdoc.getBody().appendParagraph("Mobile Number: ");
par5.setHeading(DocumentApp.ParagraphHeading.HEADING2);
CVdoc.getBody().appendParagraph(mobilenumber);
var par6 = CVdoc.getBody().appendParagraph("Objective: ");
par6.setHeading(DocumentApp.ParagraphHeading.HEADING2);
CVdoc.getBody().appendParagraph(objective);
var par7 = CVdoc.getBody().appendParagraph("Spoken Languages: ");
par7.setHeading(DocumentApp.ParagraphHeading.HEADING2);
CVdoc.getBody().appendParagraph(language);
var par8 = CVdoc.getBody().appendParagraph("Education and Degree: ");
par8.setHeading(DocumentApp.ParagraphHeading.HEADING2);
CVdoc.getBody().appendParagraph(educationwithdegree);
var par9 = CVdoc.getBody().appendParagraph("Computer Skills: ");
par9.setHeading(DocumentApp.ParagraphHeading.HEADING2);
CVdoc.getBody().appendParagraph(computerskill);
var par10 = CVdoc.getBody().appendParagraph("Training Courses: ");
par10.setHeading(DocumentApp.ParagraphHeading.HEADING2);
CVdoc.getBody().appendParagraph(TrainingCourse);
var par11 = CVdoc.getBody().appendParagraph("Hobbies: ");
par11.setHeading(DocumentApp.ParagraphHeading.HEADING2);
CVdoc.getBody().appendParagraph(Hobbies);
var par12 = CVdoc.getBody().appendParagraph("Nationality: ");
par12.setHeading(DocumentApp.ParagraphHeading.HEADING2);
CVdoc.getBody().appendParagraph(nationality);
var par13 = CVdoc.getBody().appendParagraph("Date Of Birth: ");
par13.setHeading(DocumentApp.ParagraphHeading.HEADING2);
CVdoc.getBody().appendParagraph(DOB);
var par14 = CVdoc.getBody().appendParagraph("Marital Status: ");
par14.setHeading(DocumentApp.ParagraphHeading.HEADING2);
CVdoc.getBody().appendParagraph(MaritalStatus);
CVdoc.saveAndClose();
var CVdocID = CVdoc.getId();
var url = CVdoc.getUrl();
var pdf = DocsList.getFileById(CVdocID).getAs("application/pdf");
var body = 'Here is your CV ' + pdf +'Thank you for using our Tech';
if(emailSent != EMAIL_SENT)
{
GmailApp.sendEmail(email_address, subject, body);
sheet.getRange("r2").setValue(EMAIL_SENT);
SpreadsheetApp.flush();
}
}
sheet.deleteRow(2);
}
I'm not sure how to fix what you have going on, I suspect it is structure and the fact that you're pulling 50 columns in your getRange, but really only need 17 of them (possible column width error?) Here is a script I use to procedurally generate a document from a form submission. In my case, I delete the document when I'm finished, but you'd leave it there and collect the URL and enclose it in the email you spit out. You can also use chained functions to repeat some of the repetitive tasks like copyBody.replaceText("text", variable), but if I gave you my version of that, it is more confusing since I use a lot of for() iterators, and the data in that example comes from UiApp not a form and spreadsheet combo.
function onFormSubmit(e) { // add an onsubmit trigger
var sheet = SpreadsheetApp.getActiveSheet();
var row = SpreadsheetApp.getActiveSheet().getLastRow();
//Set Unique ID for each entry
sheet.getRange(row,2).setValue(row);
// Full name and email address values come from the spreadsheet form
var email_address = "myemail#somewhere.com";//used as a reporting email for errors
var userName = e.values[1];
var date = e.values[2];
var vendor = e.values[3];
var coordinator = e.values[4];
var buyer = e.values[5];
var category = e.values[7];
var submittedBy = e.values[79];
//Values from form
var line1 = e.values[9];
var item1 = e.values[10];
var quantity1 = e.values[11];
var sku1 = e.values[12];
var price1 = e.values[13];
var total1 = e.values[14];
var line2 = e.values[16];
var item2 = e.values[17];
var quantity2 = e.values[18];
var sku2 = e.values[19];
var price2 = e.values[20];
var total2 = e.values[21];
var line3 = e.values[23];
var item3 = e.values[24];
var quantity3 = e.values[25];
var sku3 = e.values[26];
var price3 = e.values[27];
var total3 = e.values[28];
var line4 = e.values[30];
var item4 = e.values[31];
var quantity4 = e.values[32];
var sku4 = e.values[33];
var price4 = e.values[34];
var total4 = e.values[35];
var line5 = e.values[37];
var item5 = e.values[38];
var quantity5 = e.values[39];
var sku5 = e.values[40];
var price5 = e.values[41];
var total5 = e.values[42];
var line6 = e.values[44];
var item6 = e.values[45];
var quantity6 = e.values[46];
var sku6 = e.values[47];
var price6 = e.values[48];
var total6 = e.values[49];
var line7 = e.values[51];
var item7 = e.values[52];
var quantity7 = e.values[53];
var sku7 = e.values[54];
var price7 = e.values[55];
var total7 = e.values[56];
var line8 = e.values[58];
var item8 = e.values[59];
var quantity8 = e.values[60];
var sku8 = e.values[61];
var price8 = e.values[62];
var total8 = e.values[63];
var line9 = e.values[65];
var item9 = e.values[66];
var quantity9 = e.values[67];
var sku9 = e.values[68];
var price9 = e.values[69];
var total9 = e.values[70];
var line10 = e.values[72];
var item10 = e.values[73];
var quantity10 = e.values[74];
var sku10 = e.values[75];
var price10 = e.values[76];
var total10 = e.values[77];
var sumRange = sheet.getRange(1,86,sheet.getLastRow(),1);
sumRange.setNumberFormat("0,000,000.00");
sheet.getRange(row,86,1,1).setNumberFormat("0,000,000.00");
var sum = Math.round(100*(sheet.getRange(row,86,1,1).getValue())/100);
Logger.log(sum);
sheet.getRange(row,86,1,1).setNumberFormat("0,000,000.00");
Logger.log(sum);
//Document variables
var docTemplate = "Doc Id for your template document to replace text"; // *** replace with your template ID ***
var todaysDate = Utilities.formatDate(new Date(), "GMT", "MM/dd/yyyy");
var docName = "CV Document name " +userName +" on " +todaysDate;
// Get document template, copy it as a new temp doc, and save the Doc’s id
var copyId = DocsList.getFileById(docTemplate)
.makeCopy(docName)
.getId();
// Open the temporary document
var copyDoc = DocumentApp.openById(copyId);
// Get the document’s body section
var copyBody = copyDoc.getActiveSection();
// Replace place holder keys this can be iterated with a number of for() loops
// Template Header
copyBody.replaceText('keyDate', date);
copyBody.replaceText('keyVendor', vendor);
copyBody.replaceText('keyCoordinator', coordinator);
copyBody.replaceText('keyBuyer', buyer);
copyBody.replaceText('keyCategory', category);
//Template Table
copyBody.replaceText('keyLine1', line1);
copyBody.replaceText('keyItem1', item1);
copyBody.replaceText('keyQuantity1', quantity1);
copyBody.replaceText('keySKU1', sku1);
copyBody.replaceText('keyPrice1', price1);
copyBody.replaceText('keyTotal1', total1);
copyBody.replaceText('keyLine1', line1);
copyBody.replaceText('keyItem1', item1);
copyBody.replaceText('keyQuantity1', quantity1);
copyBody.replaceText('keySKU1', sku1);
copyBody.replaceText('keyPrice1', price1);
copyBody.replaceText('keyTotal1', total1);
copyBody.replaceText('keyLine2', line2);
copyBody.replaceText('keyItem2', item2);
copyBody.replaceText('keyQuantity2', quantity2);
copyBody.replaceText('keySKU2', sku2);
copyBody.replaceText('keyPrice2', price2);
copyBody.replaceText('keyTotal2', total2);
copyBody.replaceText('keyLine3', line3);
copyBody.replaceText('keyItem3', item3);
copyBody.replaceText('keyQuantity3', quantity3);
copyBody.replaceText('keySKU3', sku3);
copyBody.replaceText('keyPrice3', price3);
copyBody.replaceText('keyTotal3', total3);
copyBody.replaceText('keyLine4', line4);
copyBody.replaceText('keyItem4', item4);
copyBody.replaceText('keyQuantity4', quantity4);
copyBody.replaceText('keySKU4', sku4);
copyBody.replaceText('keyPrice4', price4);
copyBody.replaceText('keyTotal4', total4);
copyBody.replaceText('keyLine5', line5);
copyBody.replaceText('keyItem5', item5);
copyBody.replaceText('keyQuantity5', quantity5);
copyBody.replaceText('keySKU5', sku5);
copyBody.replaceText('keyPrice5', price5);
copyBody.replaceText('keyTotal5', total5);
copyBody.replaceText('keyLine6', line6);
copyBody.replaceText('keyItem6', item6);
copyBody.replaceText('keyQuantity6', quantity6);
copyBody.replaceText('keySKU6', sku6);
copyBody.replaceText('keyPrice6', price6);
copyBody.replaceText('keyTotal6', total6);
copyBody.replaceText('keyLine7', line7);
copyBody.replaceText('keyItem7', item7);
copyBody.replaceText('keyQuantity7', quantity7);
copyBody.replaceText('keySKU7', sku7);
copyBody.replaceText('keyPrice7', price7);
copyBody.replaceText('keyTotal7', total7);
copyBody.replaceText('keyLine8', line8);
copyBody.replaceText('keyItem8', item8);
copyBody.replaceText('keyQuantity8', quantity8);
copyBody.replaceText('keySKU8', sku8);
copyBody.replaceText('keyPrice8', price8);
copyBody.replaceText('keyTotal8', total8);
copyBody.replaceText('keyLine9', line9);
copyBody.replaceText('keyItem9', item9);
copyBody.replaceText('keyQuantity9', quantity9);
copyBody.replaceText('keySKU9', sku9);
copyBody.replaceText('keyPrice9', price9);
copyBody.replaceText('keyTotal9', total9);
copyBody.replaceText('keyLineA', line10);
copyBody.replaceText('keyItemA', item10);
copyBody.replaceText('keyQuantityA', quantity10);
copyBody.replaceText('keySKUA', sku10);
copyBody.replaceText('keyPriceA', price10);
copyBody.replaceText('keyTotalA', total10);
copyBody.replaceText('keySum', +sum);
// Save and close the temporary document
copyDoc.saveAndClose();
// Convert temporary document to PDF by using the getAs blob conversion
var pdf = DocsList.getFileById(copyId).getAs("application/pdf");
// Attach PDF and send the email
var subject = "CV submitted by "+submittedBy;
var body = userName +" has submitted a new CV, which is attached to this email.\nPlease ensure there are no errors before printing.\nIf there are errors, please notify: "+email_address +"\n\n";
MailApp.sendEmail(email_address, subject, body, {htmlBody: body, attachments: pdf});
// Delete temp file
DocsList.getFileById(copyId).setTrashed(true);//remove this if you added URL above for posterity
}
If you're interested I can post the iterator version of this code that makes loops for repetitive actions. Just let me know. It's a lot more complex than this example because there are a lot of function calls, but if you're comfortable with that, I'll put it up.
I know for a fact that this code will make an invoice type/shipping label document because my template is built that way. I did not change the code to your variables and needs. You will also need to build a template document with keys to replace with each user's entry values, but that isn't terribly hard. All of the formatting can be done there, and you can add headings and such in the script that read from submitted data columns so if the section (such as nationality) is left blank there's no heading or content for it.
You're looking for technique #3 in this tutorial http://googleappsdeveloper.blogspot.com/2011/10/4-ways-to-do-mail-merge-using-google.html for a guide on how to do the script I provided.
Also, be careful with body.replaceText() using keys that are numbers. When you get to 10, it will replace the text with keyText1 and add a 0 string to the end. I'd recommend using alphabet letters or words instead for your keyValues.
Here is the iterated function version of the same basic process. Ignore the UiApp lines and remove the app methods, and it will work like a form. I'm including it as an alternative to show how you can use for loops to construct a document from a template without having to hand-code it all. It's also more modular, so if I need to change something, I can just add or modify that function and not mess with the rest of it.
function doPost(e){
var app = UiApp.getActiveApplication();
var vertPanel = app.createVerticalPanel();
var grantName = e.parameter.grantName;
var userEmail = Session.getActiveUser().getEmail();
var mrNumber = e.parameter.MR;
var ss = SpreadsheetApp.openById("Id for the form response spreadsheet");
var infoSheet = ss.getSheetByName('name of the form response sheet');
var keyRow = selectKeysByGrant(grantName);
var keyHeaders = infoSheet.getRange(1,1,1,infoSheet.getLastColumn()).getValues();
var infoData = infoSheet.getRange(keyRow,1,1,infoSheet.getLastColumn()).getValues();
var keyIds = new Array (makeKeys(keyHeaders));
var dataVars = new Array (makeDataVars(keyIds));
var copyId = assignKeys(dataVars,keyIds,infoData,userEmail,mrNumber);
var pdf = mailCheatSheet(copyId,userEmail,mrNumber);
var completeLabel = app.createLabel('You should receive your worksheet results in your email soon.');
app.add(completeLabel);
return app;
}
//Select Data Row from funding type
function selectKeysByGrant(grantName){
var grant = null;
switch (grantName){
case "1":
grant = 2
break;
case "2":
grant = 3
break;
case "3":
grant = 4
break;
case "4":
grant = 5
break;
}
return grant;
}
function makeKeys(keyHeaders){
var keys = [];
for (var i = 0; i< keyHeaders[0].length; i++){
keys.push("key"+keyHeaders[0][i]);
}
return keys;
}
function makeDataVars(keyIds){
var dataVarLabels = [];
for (var k = 0; k < keyIds[0].length; k++){
dataVarLabels.push(keyIds[0][k] +"text");
}
return dataVarLabels;
}
function assignKeys(dataVars,keyIds,infoData,userEmail,mrNumber){
var variables = dataVars;
var keys = keyIds;
var rowData = infoData;
var userEmail = userEmail;
var date = Utilities.formatDate(new Date, "CST","MM/dd/yyyy");
var mrNum = mrNumber;
Logger.log(variables);
Logger.log(keys);
Logger.log(rowData);
var docTemplate = "ID of your document template";
var todaysDate = Utilities.formatDate(new Date(), "GMT", "MM/dd/yyyy");
var docName = "New name of document created submitted by " +userEmail +" on " +todaysDate;
// Get document template, copy it as a new temp doc, and save the Doc’s id
var copyId = DocsList.getFileById(docTemplate).makeCopy(docName).getId();
// Open the temporary document
var copyDoc = DocumentApp.openById(copyId);
// Get the document’s body section
var copyBody = copyDoc.getActiveSection();
for (n = 1; n < variables[0].length; n++){
copyBody.replaceText(keys[0][n].toString(),rowData[0][n].toString())
}
//replacing some text from the UIapp but isn't on the spreadsheet
copyBody.replaceText('keyUserEmail',userEmail);
copyBody.replaceText('keyDate',date);
copyBody.replaceText('keyMR',mrNum);
// Save and close the temporary document
copyDoc.saveAndClose();
return copyId;
}
function mailCheatSheet(copyId,userEmail,mrNumber){
var copyId = copyId;
var userEmail = userEmail;
var mrNum = mrNumber;
// Convert temporary document to PDF by using the getAs blob conversion
var pdf = DocsList.getFileById(copyId).getAs("application/pdf");
// Attach PDF and send the email
var subject = "SA Funding request by: "+userEmail;
var body = userEmail +" has submitted a document for " +mrNumber +", which is attached to this email.\nPlease ensure there are no errors before printing.\nIf there are errors, please notify: myself#xyz.com.\n\n";
MailApp.sendEmail(userEmail, subject, body, {name: 'CV Helperbot', htmlBody: body, attachments: pdf});
// Delete temp file
DocsList.getFileById(copyId).setTrashed(true);
return pdf;
}

Categories