2016-05-05 12 views

答えて

1

私はそれがあなたの役に立てば幸い、小さなサンプルを書いた:

<html> 
    <head> 
     <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> 
     <style> 
     select { 
     min-width: 100px; 
     float: left; 
     margin-right: 20px; 
     } 
     </style> 
    </head> 
    <body> 
     <select id="countrySelect" size="10"></select> 
     <select id="citySelect" size="10"></select> 
     <script> 
     var countries = [{name: "USA", id:1}, {name: "Canada", id:2}];    
     var cities = [{name: "New York", id:1, countryId:1}, {name: "Boston", id:2, countryId:1}, {name: "Ottawa", id:3, countryId:2}, {name: "Toronto", id:4, countryId:2}]; 

     var $countrySelect = $('#countrySelect'); 
     var $citySelect = $('#citySelect'), countrySelectHtml = ''; 
     for (var i=0; i<countries.length; i++) $countrySelect.append($('<option>').attr('value', countries[i].id).text(countries[i].name)); 

     $countrySelect.change(function() { 
      var countryId = $countrySelect.val(); 
      $citySelect.html(''); 
      for (var i=0; i<cities.length; i++) 
       if (cities[i].countryId == countryId) $citySelect.append($('<option />').attr('value', cities[i].id).text(cities[i].name)); 
     }); 

     $citySelect.change(function() { 
      alert('Selected city: ' + $(this).find('option:selected').text() + ' (id=' + $citySelect.val() + ')'); 
     }); 

     </script> 
</html> 
+0

はありがとうございました^^ –

関連する問題