0

I use the the code below from "Use jQuery to change a second select list based on the first select list option" to change a second select list based on the first select list option. It works very well. But how can I assigning the "selected" attribute to the option on this code for both selects.

JavaScript:

$(document).ready(function () {
"use strict";

var selectData, $states;

function updateSelects() {
    var cities = $.map(selectData[this.value], function (city) {
        return $("<option />").text(city);
    });
    $("#city_names").empty().append(cities);
}

$.getJSON("updateSelect.json", function (data) {
    var state;
    selectData = data;
    $states = $("#us_states").on("change", updateSelects);
    for (state in selectData) {
        $("<option />").text(state).appendTo($states);
    }
    $states.change();
    });
});

HTML:

<!DOCTYPE html>
<html>
<head>
    <title></title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
</head>
<body>
    <select id="us_states"></select>
    <select id="city_names"></select>
    <script type="text/javascript" src="updateSelect.js"></script>
</body>
</html>

JSON:

{
"NE": [
    "Smallville",
    "Bigville"
],
"CA": [
    "Sunnyvale",
    "Druryburg",
    "Vickslake"
],
"MI": [
    "Lakeside",
    "Fireside",
    "Chatsville"
    ]
}
Lewis
  • 145
  • 2
  • 2
  • 8

1 Answers1

0

You could try something like this, if you know what exact option value you are looking to select:

$(document).ready(function() {
  "use strict";

  var selectData, $states;

  function updateSelects() {
    var cities = $.map(selectData[this.value], function(city) {
      var selected = "";
      if (city == "Vickslake") {
        selected = "selected";
      }
      return $("<option " + selected + "/>").text(city);
    });
    $("#city_names").empty().append(cities);
  }

  $.getJSON("https://api.myjson.com/bins/oj1bb", function(data) {
    var state;
    selectData = data;
    $states = $("#us_states").on("change", updateSelects);
    for (state in selectData) {
      var selected = "";
      if (state == "CA") {
        selected = "selected";
      }
      $("<option " + selected + "/>").text(state).appendTo($states);
    }
    $states.change();
  });

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
  <select id="us_states"></select>
  <select id="city_names"></select>
  <script type="text/javascript" src="updateSelect.js"></script>
</body>
Woodrow
  • 2,740
  • 1
  • 14
  • 18