2

so i have json array

data = '[{"beatles": [
                {"name":"Paul McCartney","value": "http://www.paulmccartney.com"},
                {"name": "John Lennon","value": "http://www.johnlennon.it"},
                {"name":"George Harrison","value": "http://www.georgeharrison.com"},
                {"name": "Ringo Starr","value": "http://www.ringostarr.com"}],
           "stones": [
                {"name": "Mick Jagger","value": "http://www.mickjagger.com"},
                {"name": "Keith Richards","value": "http://www.keithrichards.com"}]'

and i have two dropdown lists

<html xmlns="http://www.w3.org/1999/xhtml">
     <head>
          <title></title>
          <script src="rockbands.json"></script>
          <script src="script.js"></script>
     </head>
     <body onload="getBands()">
          <select id="bands" onchange="getNames(this.value)"></select>
          <select id="names" ></select>

     </body>
</html>

so i load the dropdownlist with ID "bands" with this JS Code

function getBands() {
    var root = JSON.parse(data)
    var bandsBox = document.getElementById("bands")
    for(i in root[0]) {
        var option = document.createElement("option")
        option.text = i
        bandsBox.appendChild(option)
    }
}

what i want to do is populate the other dropdown list with ID "names" with the array element "name" based on the selection in the first dropdownlist for example if i chose beatles it would load all names in beatles

i could access it with something like root[0].beatles[1].name but i want a dynamic way to access them thanks

3
  • thats not a json array, its a string. Commented Jan 7, 2016 at 13:47
  • ah yea sorry , json string thats what i meant Commented Jan 7, 2016 at 13:48
  • 1
    See this -- jsfiddle.net/abhitalks/05ejeunh Commented Jan 7, 2016 at 14:24

2 Answers 2

2

in your getNames() function do something like

function getNames(nameOfBand) {
    var root = JSON.parse(data);
    var namesBox = document.getElementById("names");
    var listOfNames = root[0][nameOfBand]
    for( j = 0; j < listOfNames.length; j++) {
        var option = document.createElement("option");
        option.text = listOfNames[j]["name"];
        namesBox.appendChild(option)
    }
}
Sign up to request clarification or add additional context in comments.

Comments

1

Based on this document:

Property accessors provide access to an object's properties by using the dot notation or the bracket notation.

object.property
object["property"]

Which means you can access properties like root[0]['beatles'][1]['name'] as well.

And since 'beatles' is a string acting like property, it can be a variable too:

root[0][band_name][1]['name']

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.