Javascript to access array in array with input variable

I am developing a form that handles input differently depending on the state the user is in. In my web page, I have a list of states in a dropdown:

<div class="top-row" title="Select the proper state from the list."> <select name="state-list" class="state-list" id="stateList" > <option value=30>Select State</option> <option value=0>AL</option> <option value=1>AR</option> <option value=2>CA</option> <option value=3>CT</option> <option value=4>DE</option> <option value=5>DC</option> <option value=6>GA</option> </select> </div>



In my javascript file, I created an array called states and posted it as arrays:

var state = { AL: [false, true, true, 0], AZ: [false, false, false, 0],
AR: [false, true, true, 0], CA: [false, false, false, 0], 
CT: [false, true, true, 0], DE: [false, true, true, 0],
DC: [false, true, true, 0], GA: [false, true, true, 0]};

      


The problem I am facing is finding the value of the array. I searched a lot but I just couldn't find a solution.

findState = document.getElementById('stateList').value;
console.log(state.findState[0]);

      


They all return undefined, but the 'findState' value does matter. How can I access the values โ€‹โ€‹of a particular state array in the state array?

+3


source to share


2 answers


Your expression is trying to access a property of an findState

object state

and has no property named findState

. Use a convention instead:

console.log(state[findState][0]);

      



Also, don't forget to do the correct null / undefined checks the account for the possibility that the value could not be found (for example, if the user re-selects the first option in the dropdown).

+4


source


You didn't create an array ( []

) called state, you created an object ( {}

) called state.

In it, each abbreviation "state" is a key, and a true / false parameter is a value.

Objects do not guarantee the order of their content, so you cannot search them by numeric index. You can either recycle state

to actually be an array of objects, or recycle how you access the values.

findState

does not return the expected value. First you need to check the selected index, then get either the property value

(numeric attr value) or the text.



var stateList = document.getElementById('stateList'); //the whole list in the DOM
var selectedState = stateList.options[stateList.selectedIndex]; //whichever one is selected
var numericValue = selectedState.value //value='#'
var textAbbrev = selectedState.text //"AR" , "AZ", etc

      

With an object using abbreviations as "key" you want .text

var optionsArray = state.textAbbrev //should give you the entire array for selected state 
console.log(optionsArray[0]); //should show the 1st true/false value in the selected state array.

      

Also, your HTML is missing "AZ".

+1


source







All Articles