How to make client side script variable dynamic within a repeat - javascript

I am trying to output som script using SSJS from a computedField like so:
var outScript = "<script>var data = " + datad.toString() + ";</script>"
The problem I have is that the computedField is within a doccollection repeat so I need to make the variable dynamic because I later need to access only the variable from the current entry using client side javascript (also within repeat)
How do I write to make the "data" variable dynamic within my repeat?
I know can create the variable using noteid or index, but I need to know how to write to output the variable i.e data1, data2 etc.
Hope you understand, a bit complicated to explain.
problably an easy answer I havn't thought of
thanks
Thomas

You could use the repeat's indexVar to save the data with a distinct key for each repeat entry:
var outScript = "<script>window.data_myRepeat_" + iRepeat.toFixed(0) + " = " + datad.toString() + ";</script>"
Here, it is assumed that the repeat's ID is "myRepeat" and indexVar is "iRepeat".

Related

Correct way to convert your JavaScript function into a string so it can be inserted into innerHTML

This is what I am doing: I am building a fun in house API Voting System. I am using a client side snippet insert onto page
Like this:
<script src="domain.com/api/scripts/main.js"></script>
<div id="content-wrap" id="ac1e435e-c564-48f8-9f45-338616e7a789"></div>
Now in my main .JS I do all ajax request and modify the #content-wrap with creating new elements and inserting additional JS required to run Voting System.
However big issue I am experiencing is when I write JavaScript that I need to insert into #content-wrap I am currently writing it like this:
script.innerHTML = "$(someting).on('click', funciton(){"
+ "$.ajax({type: 'post',"
+ " url: '" + base + "/api/request', data: $('form').serialize(), "
+ "success: function(response){";
As you can see that can cause lot of issues as I build on it.
What is better way to accomplish this or is there a way i can just write my script / code and do something like this.
script.innerHTML = ConvertToString(script.js) OR ConvertToString(function X);
ConvertToString is just an expression I am using to explain what I would like to do instead of what I am doing.
Thank you, I am open to any suggestions.
I also must do this in plain JavaScript or with jQuery library so any suggestions to use VueJs, AngularJS or React will be considered as future references.
Thank you again
Additional explanation:
I would like to insert into my script element JavaScript snippet. But my snippet is about 30 lines long currently and might get bigger with time so it is very difficult to code with all the + " code " on every line that I write so that it can be inserted with innerHTML into element and executed on Client end.
So I would instead like to do something like this
element.innerHTML = mysnippetcode // but with out using + "" on each line like shown above
OR
element.append(snippet)
I hope this makes it little more clear
Solution that worked for me was using back ticks to wrap my sinppet and insert it into innerHTML of the element..
Just use the function's name without the () to convert it to a string:
function foo() {
var a = 10;
var b = 20;
var c = a + b;
return c;
}
document.write(foo);
The document.write will result in this string:
function foo() { var a = 10; var b = 20; var c = a + b; return c; }
If you only want the function's body, then you could just normally remove the first and last characters of the string.
I am not entirely sure this is what you wanted, if not, please make yourself more clear.
Alternatively, you could do an eval([insert function code here]) and there would be no need to add the code to the innterHTML of the script, read up on that function if you haven't heard of it.
Or if you want to create a function from a string, you can use new Function([name] ,[function body string]) if you need arguments you have to sandwich them between the 2 parameters.
But my snippet is about 30 lines long currently and might get bigger with time > so it is very difficult to code with all the + " code " on every line that I
write
You can use template literals if you want multi-line strings in Javascript, you simply have to replace your quotes with backticks.
See this MDN page if you are interested, or even this StackOverflow answer.

Create javascript string with conditional and non conditional variables

I'm creating a single string using some defined variables like so:
var name = 'John';
var business = 'Google';
var email = name + ' registered the business ' + business;
In reality this is from a form submission so the variables will be set in a form and sent to my NodeJS backend to create this string. The user may or may not enter a message. I've created an if statement to add it to the string if they have:
if (message) email += '<br /><br />Message: ' + message;
The problem is when I expand this logic, it can get very messy. For example if I want to add several conditional variables to various points in the middle of the original string. Is there a way to do the conditional logic inside the initial string build?
Use a ternary operator. It can still get messy, but it reduces "if" everywhere.
var email = name + ' registered ' + business
+ (message ? '<br /><br />Message: ' : '') // conditional line
+ more_stuff...;
There are many ways you could structure the code to clean things up. A simple solution would be creating an object that keeps track of your various inputs, and then you could loop through that object to append all necessary items.
For example:
var obj = {
message: messageField,
messageTwo: messageTwoField
}
for (keys in obj){
if (key == message && obj.key) {
//append the string to a specific place
}
}
There are many ways to potentially solve this, but by storing everything in one object that can help to clean things up. Also, the if statement is conditional based on the key name and if there is a value assigned to that key name. This of course is just my opinion on how you could approach this, the size and complexity of the app could greatly change this answer.

Adding and Displaying Array Issue

var reset = function ()
{
var p = parseFloat($("#IA").val());
var q = parseFloat($("#IB").val());
var m = parseFloat($("#CGCD").val());
var aR = [];
aR += ["GCD(" + p + "," + q + ")=" + m];
document.getElementById("PGCD").innerHTML = aR + "\n";
document.getElementById("IA-error").innerHTML="";
document.getElementById("IB-error").innerHTML="";
$("#IA").focus();
};
The code above is only for a 'reset' function, a part of additional code (not present), the purpose which is to find the Greatest Common Denominator, GCD.
My 'reset' function is connected to a button, #reset, the purpose of which is to do four things:
add and store the string GCD(p,q)=m to the array 'aR'; p/q/m are variable stand-ins for the values of the input text areas #IA, #IB, and #CGCD (the GCD of #IA and #IB);
display the array 'aR' in a text-area #PGCD each time the reset button is clicked; this is why I used an array;
clear the two input text areas #IA and #IB;
clear the one output text area;
As it stands, all four objectives are completed successfully, with one exception: for the second objective, only the most recent GCD calculation is outputted; none of the previous calculations output.
I cannot get the array to list the different saved calculations within it. I think (?) the new calculations are being added to the array, but I am not sure.
I've tried a 'for' statement, and an 'if' statement, neither of which worked. I don't know whether I coded it wrong, or if it wasn't the right solution for my issue.
I tried to search the forums (here) for a solution, but was unable to find one.
Thank you.
If I'm understanding what you are describing, I believe your problem is that you are attempting to use += to add elements to an array. You should use
aR.push("GCD(" + p + "," + q + ")=" + m);
The += operator is used for addition of a value to itself as well as string concatenation.
Edit: per comments below, the main issue was declaration of aR as a local variable. It needs to be either global or declared within the same scope.

Trying to reduce repetition of javascript using a variable

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.

Accessing Variables in Javascript using .length

I'm pretty new to Javascript, so forgive me if this is a simple question.
I'm trying to access the length of a set of checkboxes in a form using Javascript. However, I need to be able to change the "name" field of the checkboxes to check several different sets of them. Right now, my sample code looks like:
var set = "set" + x;
totalLength = optionBoxes.set.length;
The variable x is being incremented by a for loop that wraps the whole thing and the name of the checkbox sets that I'm trying to access are set0, set1, set2, etc.
Thanks.
Edit: small typo fixes
Probably you want this:
var set = "set" + x;
totalLength = optionBoxes[set].length;
In Javascript, properties of an object are usually accessed as object.name, but they can also be accessed by object["name"] if you have the name as a string.
if you think that your code should otherwise work try:
totalLength = optionBoxes[set].length;

Categories