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):選択したものに付随する何かを表示2</h1>
  11. 「選択したものに付随する何かを表示1」と同じコトを別記述でする。
  12. <p>
  13.   <!-- Same as example 3, except the <select> box expressed as follows: -->
  14.   <select data-bind="options: availableCountries, optionsText: function(item) {
  15.                         return item.countryName + ' (pop: ' + item.countryPopulation + ')'
  16.                       },
  17.                       value: selectedCountry,
  18.                       optionsCaption: 'Choose...'"></select><br />
  19. </p>
  20.  
  21. <div data-bind="visible: selectedCountry"> <!-- Appears when you select something -->
  22.   You have chosen a country with population
  23.   <span data-bind="text: selectedCountry() ? selectedCountry().countryPopulation : 'unknown'"></span>.
  24. </div>
  25.  
  26. <script type="text/javascript">
  27.   // Constructor for an object with two properties
  28.   var country = function(name, population) {
  29.     this.countryName = name;
  30.     this.countryPopulation = population;
  31.   };
  32.   var viewModel = {
  33.     availableCountries : ko.observableArray([
  34.       new country("UK", 65000000),
  35.       new country("USA", 320000000),
  36.       new country("Sweden", 29000000)
  37.     ]),
  38.     selectedCountry : ko.observable() // Nothing selected by default
  39.   };
  40.   ko.applyBindings(viewModel);
  41. </script>
  42. <div style="font-size:10pt;text-align:right;margin-top:0.5em;">
  43. <a href="//tips.recatnap.info/" target="_top">PCスキルの小技・忘却防止メモ</a> -
  44. <a href="//tips.recatnap.info/wiki/" target="_top">PCスキルの小技・忘却防止メモのまとめ(wiki)</a>
  45. </div>
  46. <div style="font-size:10pt;text-align:center;margin-top:0.5em;padding:0.5em;border-top:1px solid #ccc;">
  47. Copyright &copy; 2009 by PCスキルの小技・忘却防止メモ. All rights reserved.
  48. </div>
  49. </body>
  50. </html>