These forums are amazing and the contributors I've been helped by are really talented. So I keep coming back everytime I can't solve my own problems or am not understanding a programming concept. This is certainly one of the latter times!
With the help I've received so far, I've managed to develop a complicated form in which the end user will mostly click a series of checkboxes and enter some data into a few textfields. The result of these actions will populate some textboxes with various text, based on the aforementioned actions.
The text that populates the textareas is referenced within a few object literals by each checkbox. This works just fine and the site is quite useable.
In my object literals, I have name:value pairs in which the 'value' is a string of text. I've been trying to include a variable within some name:value pairs to no success. This always breaks the script because the variable is never defined / has a 'null' value on page load.
For example,
Instead of
var example = {
var1:'some string',
var2:'some other string'
}
I tried,
var somevariable = document.getElementById('someId');
var example = {
var1: 'some string' + somevariable + 'some other bit',
var2: 'some other string'
}
My question is whether including a variable referenced elsewhere in the script can be incorporated within the name:value pair in an object literal?
For reference (and because it is a rather long script), my site is: http://www.hematogones.com/bmbiopsies.html.
The trick with an object literal is that it is evaluated immediately; there is no "easy" way to delay the value you get.
var x = "Alice";
var obj = { greeting: "Hello, " + x + "." };
console.log(obj.greeting); // "Hello, Alice."
x = "Bob";
console.log(obj.greeting); // "Hello, Alice."
obj = { greeting: "Hello, " + x + "." };
console.log(obj.greeting); // "Hello, Bob."
Something to come back to later:
If you really really really need to put a variable into a string literal you define later, you could create an inline function. This way, instead of obj.greeting
being a simple string, it is a function that you call (which will look like obj.greeting()
).This means that instead of the string value being calculated when you declare your object, it will be declared when you call the function. This is a very powerful feature of Javascript called "closures" and you could spend all day learning about the behaviors, expected and unexpected, that you get with them.
var x = "Alice";
var obj = { greeting: function() { return "Hello, " + x + "." }};
console.log(obj.greeting()); // "Hello, Alice."
x = "Bob";
console.log(obj.greeting()); // "Hello, Bob."