简体   繁体   中英

Add certain values from JSON object to javascript array

Update: I've tried the suggestions in the comments and it's still not working. I really have no idea why. I've consolidated it to a single loop and fixed the syntax errors noted. Here's the code as it looks now:

    $(function() {

  $("#json-one").change(function() {

    var $dropdown = $(this);

    $.getJSON("washroutines.json", function(data) {

      var vals = [];
      var $jsontwo = $("#json-two");
$jsontwo.empty();        

      for (var i = 0; i < data.length; i++){
        if (data[i].make === $dropdown.val()) {
          $jsontwo.append("<option value=\"" + data[i].model + "\">" + data[i].model + "</option>");
        }
      }

    });
  });

});

Any additional help would be much appreciated!

Original question:

I'm trying to create dependent drop down menus using a json object, and I'm having trouble getting the second menu to populate based on the first. When the first menu changes, the second goes to a bunch of "undefined"s.

    $.getJSON("washroutines.json", function(data) {     
      var vals = [];

for (i = 0; i < data.length; i++){
 if (data.make = $dropdown.val()) {
   vals.push(data.model);
   }
  }

      var $jsontwo = $("#json-two");
      $jsontwo.empty();
   for (i = 0; i < vals.length; i++){
   $jsontwo.append("<option value\"" + vals[i] + "\">" + vals[i] + "</option>");
}

Please use small words when explaining things to me, I'm new at this!

contents of the JSON:

[{"make":"Maytag","model":"Bravos","prewashCycle":"Whitest Whites"},
{"make":"Maytag","model":"Awesome","prewashCycle":"Awesome Whitest Whites"},
{"make":"Whirlpool","model":"Cabrio","prewashCycle":"Extra Heavy"},
{"make":"Kenmore","model":"Elite","prewashCycle":"Awesome"}]

Try changing your for loop for this

for (var i = 0; i < data.length; i++){
  if (data[i].make === $dropdown.val()) {
    vals.push(data[i].model);
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM