Reputation: 1
I am working on a jquery form file that uses an array to populate a dropdown of sizes based on the selection of the material. This works fine but now we are adding an additional dropdown and we need to have different values in the array based on that selection.
this is the part of the current working code:
var Material = new Array();
Material['UNC'] = new Array('40', '32');
Material['UNF'] = new Array('10', '24');
This is basically what I am trying to, not sure how:
if($("#style").val() == "long") { var Material = new Array();
Material['UNC'] = new Array('45', '35');
Material['UNF'] = new Array('15', '29');} else {
var Material = new Array();
Material['UNC'] = new Array('40', '32');
Material['UNF'] = new Array('10', '24');}
I'm not having any luck, I'm not super familiar with Javascript functions. Thanks
Upvotes: 0
Views: 1170
Reputation: 234795
You just need to move the declaration of the Material
variable outside the blocks:
var Material = new Array();
if($("#style").val() == "long") {
Material['UNC'] = new Array('45', '35');
Material['UNF'] = new Array('15', '29');
} else {
Material['UNC'] = new Array('40', '32');
Material['UNF'] = new Array('10', '24');
}
However, as others have pointed out, you should be using an object rather than an array for these kinds of non-numeric indexes. You should also use object and array notation:
var Material = {};
if($("#style").val() == "long") {
Material['UNC'] = ['45', '35'];
Material['UNF'] = ['15', '29'];
} else {
Material['UNC'] = ['40', '32'];
Material['UNF'] = ['10', '24'];
}
Upvotes: 0
Reputation: 14419
One way:
var isLong = $('#style').val() === 'long';
var material = {};
material.UNC = (isLong) ? [45, 35] : [40, 32];
material.UNF = (isLong) ? [15, 29] : [10, 24];
Another way:
var isLong = $('#style').val() === 'long';
var material = {};
if (isLong) {
material.UNC = [45, 35];
material.UNF = [15, 29];
}
else {
material.UNC = [40, 32];
material.UNF = [10, 24];
}
As Felix Kling points out, it is better to use an object over an array for material. I've also used JavaScript convention of a lowercase variable name. Instead of using new Array
use []
and instead of new Object
, you can use {}
.
Upvotes: 2