0

From my DOM element, I let the user choose a state.

In my code I go:

 var State = $("select[name=state1]").val();

So if AZ was selected, the ouput would be State == "AZ"

Then I have arrays for every state so for example:

var AZ =[[1],[2]];

And I fill each array with some data. Then I try to do a calculation that looks like this:

var ABC = 25 * State[0][1];

However, the variable state isn't an array. I want state replaced by the chosen one, for example it might be AZ so I actually want to calculate...

 var ABC = 25 * AZ[0][1];

Any ideas on how I can pass the value of State into last equation automatically?

2 Answers 2

1

I suggest assigning your state values a little differently:

var states = {
    AZ: [[1],[2]],
    //and so on
};

Then you can do

var ABC = 25 * states[State][0][1];
Sign up to request clarification or add additional context in comments.

11 Comments

I dont understand what AZ: [[1][2]] does. State returns "AZ" from the DOM and then I want to call element AZ[1][2] by typing State[1][2]
Basically the bottommost expression expands to 25 * the 2nd element of the array associated with attribute "AZ" of states (25 * 2)
AZ is an array, that contains 2 arrays, with one element each. What were you expecting?
So, {AZ: [[1,2,3],[4,5,6]]}?
I think you should read about how objects and arrays work in JavaScript. Let's say you want to change the 4 to a 7. You would do states.AZ[1][0] = 7; or states["AZ"][1][0] = 7;
|
1

Change your state to be an object to contain state arrays:

var state = { AZ : [[1],[2]], OS : [[3], [4]] };
var abc = 25 * state["AZ"][0]

12 Comments

What is OS? and what does the : do here?
I'll take a guess and say it's an arbitrary state abbreviation data point used just as an example... And : assigns the array to the object's named data point.
@Badrush Just like jTitus said, 'OS' could be anything, just an example of another state, and : is how you assign values to object's properties.
Okay, but if I am defining state as var State = $("select[name=state1]").val(); I cannot make state a bunch of arrays. I basically get a string from the user, which I need to use to find the array whose name matches that string.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.