I'm trying to retrieve an array value where the key is a variable. JSFiddle here -- type 'apparel' or 'books' into the industry input. The output of the JSFiddle states that the value returned is undefined.
The problem lies in var filename = constants.factsheet - how can I correctly pass the value of factsheet to retrieve the associated filename?
JS:
$(function () {
var availableIndustries = ["apparel", "books"];
$("#industry").autocomplete({
source: availableIndustries
});
$("input[type=image]")
.button()
.click(function (event) {
var constants = {
'apparel': 'apparel.pdf',
'books': 'publishing.pdf',
};
var factsheet = document.getElementById('industry').value;
var filename = constants.factsheet;
$('#factsheet').text('Your factsheet is ' + factsheet);
$('#file').text('Your filename is ' + filename);
});
});
3 Answers 3
Change:
var filename = constants.factsheet;
to:
var filename = constants[factsheet];
(Note that your constants is not an array. It's an object.)
In JavaScript, you can access object properties in two ways: Using dot notation and a literal property name (constants.apparel), or using bracketed notation and a string property name (constants["apparel"]). In the second case, the string can be the result of any expression, including a variable lookup. So these all show the same thing:
// Dot notation
console.log(constants.apparel);
// Brackets with string literal
console.log(constants["apparel"]);
// Brackets with concatentation expression
console.log(constants["app" + "arel"]);
// Brackets using a variable
var name = "apparel";
console.log(constants[name]);
// Brackets using the return value of a function
function foo() { return "apparel"; }
console.log(constants[foo()]);
You get the idea.
1 Comment
T.J. Crowder is right about using bracket syntax for looking-up objects by a variable key name, I just optimized things a bit by moving your static files object constant out of the event function (no need to generate that each time), and cached the #industry element reference.
$(function () {
var industryInput = $('#industry'),
availableIndustries = ['apparel', 'books'],
files = {
'apparel': 'apparel.pdf',
'books': 'publishing.pdf'
};
industryInput.autocomplete({
source: availableIndustries
});
$('input[type=image]').button().click(function (event) {
var factsheet = industryInput.value;
$('#factsheet').text('Your factsheet is ' + factsheet);
$('#file').text('Your filename is ' + files[factsheet]);
});
});
Comments
I post the above answer the way it applies to you in your code.
$(function () {
var availableIndustries = ["apparel", "books"];
$("#industry").autocomplete({
source: availableIndustries
});
$("input[type=image]")
.button()
.click(function (event) {
var constants = {
'apparel': 'apparel.pdf',
'books': 'publishing.pdf',
};
var factsheet = document.getElementById('industry').value;
var filename = constants[factsheet];
$('#factsheet').text('Your factsheet is ' + factsheet);
$('#file').text('Your filename is ' + filename);
});
});