Trying to reduce repetition of javascript using a variable - javascript

I am trying to reduce the repetition in my code but not having any luck. I reduced the code down to its simplest functionality to try and get it to work.
The idea is to take the last two letters of an id name, as those letters are the same as a previously declared variable and use it to refer to the old variable.
I used the alert to test whether I was getting the right output and the alert window pops up saying "E1". So I am not really sure why it wont work when I try and use it.
E1 = new Audio('audio/E1.ogg');
$('#noteE1').click(function() {
var fileName = this.id.slice(4);
//alert(fileName); used to test output
fileName.play();
$('#note' + fileName).addClass('active');
});
The code block works when I use the original variable E1 instead of fileName. I want to use fileName because I am hoping to have this function work for multiple elements on click, instead of having it repeated for each element.
How can I make this work? What am I missing?
Thanks.

fileName is still a string. JavaScript does not know that you want to use the variable with the same name. You are calling the play() method on a string, which of course does not exist (hence you get an error).
Suggestion:
Store your objects in a table:
var files = {
E1: new Audio('audio/E1.ogg')
};
$('#noteE1').click(function() {
var fileName = this.id.slice(4);
//alert(fileName); used to test output
files[fileName].play();
$('#note' + fileName).addClass('active');
});
Another suggestion:
Instead of using the ID to hold information about the file, consider using HTML5 data attributes:
<div id="#note" data-filename="E1">Something</div>
Then you can get the name with:
var filename = $('#note').data('filename');
This makes your code more flexible. You are not dependent on giving the elements an ID in a specific format.

Related

Form's App Script does not replace fields in template accurately

I have a simple script to generate a doc and PDF upon form submission. It worked well on simple template (e.g. Only 1 sentence, First name, Last name and Company name).
However, when I use a template that's longer, having many fields, and formatting, the code runs but replace the text randomly.
I have tried to hardcode the fields of forms in ascending order as the doc template. However it still replace the text randomly
Can anybody points out what have I done wrong?
My code:
function myFunction(e) {
var response = e.response;
var timestamp = response.getTimestamp();
var [companyName, country, totalEmployees,totalPctWomenEmployees,numberNationality,name1,position1,emailAdd1,linkedin1,funFact1,name2,position2,emailAdd2,linkedin2,gameStage,gameStory] = response.getItemResponses().map(function(f) {return f.getResponse()});
var file = DriveApp.getFileById('XXXXX');
var folder = DriveApp.getFolderById('XXXXX')
var copy = file.makeCopy(companyName + '_one pager', folder);
var doc = DocumentApp.openById(copy.getId());
var body = doc.getBody();
body.replaceText('{{Company Name}}', companyName);
body.replaceText('{{Name}}', name1);
body.replaceText('{{Position}}', position1);
body.replaceText('{{Email}}', emailAdd1);
body.replaceText('{{Linkedin}}', linkedin1);
body.replaceText('{{Fun Fact}}', funFact1);
body.replaceText('{{Game Stage}}', gameStage);
body.replaceText('{{Game Story}}', gameStory);
doc.saveAndClose();
folder.createFile(doc.getAs("application/pdf"));}
My template -
Result -
Question - Does that mean the array declaration in line 3 was supposed to match the order of my form responses columns?
You can use Regular Expresion:
body.replace(/{{Company Name}}/g, companyName); // /g replace globaly all value like {{Company Name}}
Finally I found what have went wrong after so many trials and errors!
The reason is because I declared the array variables randomly without following the order of the form responses columns.
The issue is with the part -
var [companyName, country, totalEmployees,totalPctWomenEmployees,numberNationality,name1,position1,emailAdd1,linkedin1,funFact1,name2,position2,emailAdd2,linkedin2,gameStage,gameStory] = response.getItemResponses().map(function(f) {return f.getResponse()});
It's actually pulling responses from the spreadsheet, and should be corrected in order. The wrongly mapped values was what causing the replacement of text went haywire. I corrected the order as per form responses and it is all good now.
Learning points:
If you swapped around the variables, what response.getItemResponses().map(function(f) {return f.getResponse()} does is that it will go through the form responses column by column in order, and it will map the content to the wrong variable. As a result, when you replace your text later using body.replaceText('{{Game Stage}}', gameStage), there might be possibility that whatever stored in gameStage might be name1. Hence the replaced text will be wrong. And you will scratch your head until it bleeds without knowing why.
I saw #Tanaike's comment after I found the answer, but totally spot on!

javascript how to insert new elements at different locations in page

I'm writing a chrome extension that will add helper text instructions/reminders to specific location in the "new order" form we use at work. I'm really new to coding (basically using this project as a way to learn). I've created something that works - but I'm convinced there's a more elegant solution that I just haven't been able to figure out.
var helpText = "this is the message"
var customAlert = makeAlert(helpText) //create html container for msg
function makerAlert(helpText){...} //createElem, add class/style, append children
I'm okay with that bit (above). But should i be storing information on each message in objects instead? why would/wouldn't i? what information would go in it?
function alertPlacer(customAlert){
var par = document.getElementsByClassName("class-name")[i];
var sib = par.childNodes[j];
par.insertBefore(customAlert, sib);
};
really struggling with this bit (above). I have actually made alertPlacer() functions for each message because i can't figure out how to create a function that will take different class name & index parameters. should i be breaking this up more? if i stored these bits of info in an object, would that be useful?
relevant info:
because the target locations are within a form, almost nothing has an "id" attribute. so i have to use getElementsByClassName & an index.
for each message, I know the target parent className & index and the child node index to "insert before".
i would like to stick with javascript-only solution.
functions can take multiple arguments:
function alertPlacer(customAlert,className,parIndex,childIndex){
var par = document.getElementsByClassName(className)[parIndex]; var sib = par.childNodes[childIndex];
par.insertBefore(customAlert, sib);
};
And you call your function like
alertPlacer(yourAlert,"class-name",6,9);

JSON element detection

I’ve created a string…
{"atts": [{"name": "wedw"}, {"type": "---"}]}
I pile a bunch of these together in an array based on user input and attach them to another string to complete a JSON object that tests out as valid.
So I end up with a global array called fields with a bunch of these little snippets.
So how do I change the name "weds" with a new name? I’ve tried...
function changefieldname(pos){
var obj = JSON.parse(jsonstring);
var oldname = obj.tracelog.fields[pos].atts[0]["name"];
var newname = document.getElementById("newlogfieldname"+pos).value;
fields[pos].replace(oldname, newname);
//writejson();
}
And a bunch of variations. I know everything is checking out correct interms of the variables pos, oldname, and newname. I also know that fields[pos] returns the string in the array I want to correct but it’s not happy. I also tried converting fields[pos] to a string, but the replace function doesn't work on it. I’m sure there is a good reason.
Why even bother trying to do some kind of replacement? Just assign it a new value:
obj.tracelog.fields[pos].atts[0]["name"] = newname;

JQuery and Eval

First of all, lets say I have about 10 divs that are hidden and have the ID's as "modal1", "modal2", "modal3", etc... Using an ajax request, the data returned contains an ID number, lets say it is 7.
In previous tasks, I have used the javascript eval function but this does not work. I wish to append the received data to the correct modal div.
var newdataobj = JSON.parse(newdata);
var ResponseDiv = "#modal" + newdataobj.ID;
$(eval(ResponseDiv)).append(newdataobj.DataToAdd);
This doesn't work and the script stops working at this point. I have also tries using the JQuery version of eval, but that did not work either.
You don't need to use eval() here, use just $(ResponseDiv).append(newdataobj.DataToAdd);
ResponseDiv is already a string and that is what you need for the selector.
Try this to confirm you have the right ID:
var newdataobj = JSON.parse(newdata);
var ResponseDiv = "#modal" + newdataobj.ID;
alert(ResponseDiv); // or console.log(ResponseDiv); - to doublecheck you have the right ID
$(ResponseDiv).append(newdataobj.DataToAdd);
ResponseDiv is already a string containing exactly what you want.
You don't want eval at all.

How do I concatenate a string with a variable?

So I am trying to make a string out of a string and a passed variable(which is a number).
How do I do that?
I have something like this:
function AddBorder(id){
document.getElementById('horseThumb_'+id).className='hand positionLeft'
}
So how do I get that 'horseThumb' and an id into one string?
I tried all the various options, I also googled and besides learning that I can insert a variable in string like this getElementById("horseThumb_{$id}") <-- (didn't work for me, I don't know why) I found nothing useful. So any help would be very appreciated.
Your code is correct. Perhaps your problem is that you are not passing an ID to the AddBorder function, or that an element with that ID does not exist. Or you might be running your function before the element in question is accessible through the browser's DOM.
Since ECMAScript 2015, you can also use template literals (aka template strings):
document.getElementById(`horseThumb_${id}`).className = "hand positionLeft";
To identify the first case or determine the cause of the second case, add these as the first lines inside the function:
alert('ID number: ' + id);
alert('Return value of gEBI: ' + document.getElementById('horseThumb_' + id));
That will open pop-up windows each time the function is called, with the value of id and the return value of document.getElementById. If you get undefined for the ID number pop-up, you are not passing an argument to the function. If the ID does not exist, you would get your (incorrect?) ID number in the first pop-up but get null in the second.
The third case would happen if your web page looks like this, trying to run AddBorder while the page is still loading:
<head>
<title>My Web Page</title>
<script>
function AddBorder(id) {
...
}
AddBorder(42); // Won't work; the page hasn't completely loaded yet!
</script>
</head>
To fix this, put all the code that uses AddBorder inside an onload event handler:
// Can only have one of these per page
window.onload = function() {
...
AddBorder(42);
...
}
// Or can have any number of these on a page
function doWhatever() {
...
AddBorder(42);
...
}
if(window.addEventListener) window.addEventListener('load', doWhatever, false);
else window.attachEvent('onload', doWhatever);
In javascript the "+" operator is used to add numbers or to concatenate strings.
if one of the operands is a string "+" concatenates, and if it is only numbers it adds them.
example:
1+2+3 == 6
"1"+2+3 == "123"
This can happen because java script allows white spaces sometimes if a string is concatenated with a number. try removing the spaces and create a string and then pass it into getElementById.
example:
var str = 'horseThumb_'+id;
str = str.replace(/^\s+|\s+$/g,"");
function AddBorder(id){
document.getElementById(str).className='hand positionLeft'
}
It's just like you did. And I'll give you a small tip for these kind of silly things: just use the browser url box to try js syntax. for example, write this: javascript:alert("test"+5) and you have your answer.
The problem in your code is probably that this element does not exist in your document... maybe it's inside a form or something. You can test this too by writing in the url: javascript:alert(document.horseThumb_5) to check where your mistake is.
Another way to do it simpler using jquery.
sample:
function add(product_id){
// the code to add the product
//updating the div, here I just change the text inside the div.
//You can do anything with jquery, like change style, border etc.
$("#added_"+product_id).html('the product was added to list');
}
Where product_id is the javascript var and$("#added_"+product_id) is a div id concatenated with product_id, the var from function add.
Best Regards!

Categories