javascript - Add selected for jQuery to change a second select list based on the first select list option -


i use the code below "use jquery change second select list based on first select list option" change second select list based on first select list option. works well. how can assigning "selected" attribute option on code 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);     (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"     ] } 

you try this, if know exact option value looking 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);      (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>


Comments

Popular posts from this blog

node.js - Node js - Trying to send POST request, but it is not loading javascript content -

javascript - Replicate keyboard event with html button -

javascript - Web audio api 5.1 surround example not working in firefox -