knockoutjs:Using built-in bindings:Working with form fields:options

  1. <!DOCTYPE html>
  2. <html lang="ja">
  3. <head>
  4. <meta charset="UTF-8">
  5. <title>knockoutjs:Using built-in bindings:Working with form fields:options</title>
  6. <script type="text/javascript" src="jquery-1.5.1.min.js"></script>
  7. <script type="text/javascript" src="knockout-2.1.0beta.js"></script>
  8. </head>
  9. <body>
  10. <h1>optionsバインディング(knockoutjs):選択したものに付随する何かを表示1</h1>
  11. <p>
  12.     Your country:
  13.     <select data-bind="options: availableCountries, 
  14.                        optionsText: 'countryName', 
  15.                        value: selectedCountry, 
  16.                        optionsCaption: 'Choose...'"></select>
  17. </p>
  18.  
  19. <div data-bind="visible: selectedCountry"> <!-- Appears when you select something -->
  20.   You have chosen a country with population
  21.   <span data-bind="text: selectedCountry() ? selectedCountry().countryPopulation : 'unknown'"></span>.
  22. </div>
  23.  
  24. <script type="text/javascript">
  25.   // Constructor for an object with two properties
  26.   var country = function(name, population) {
  27.     this.countryName = name;
  28.     this.countryPopulation = population;
  29.   };
  30.   var viewModel = {
  31.     availableCountries : ko.observableArray([
  32.       new country("UK", 65000000),
  33.       new country("USA", 320000000),
  34.       new country("Sweden", 29000000)
  35.     ]),
  36.     selectedCountry : ko.observable() // Nothing selected by default
  37.   };
  38.   ko.applyBindings(viewModel);
  39. </script>
  40. <div style="font-size:10pt;text-align:right;margin-top:0.5em;">
  41. <a href="//tips.recatnap.info/" target="_top">PCスキルの小技・忘却防止メモ</a> -
  42. <a href="//tips.recatnap.info/wiki/" target="_top">PCスキルの小技・忘却防止メモのまとめ(wiki)</a>
  43. </div>
  44. <div style="font-size:10pt;text-align:center;margin-top:0.5em;padding:0.5em;border-top:1px solid #ccc;">
  45. Copyright &copy; 2009 by PCスキルの小技・忘却防止メモ. All rights reserved.
  46. </div>
  47. </body>
  48. </html>