Knockout.JS - Options (Complete)
by Marventus
HTML
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.0/knockout-min.js"></script>
<h2>Modelo de vista</h2>
<h4>Options completo - como objeto</h4>
<form class="fifty">
<p><strong>Available Countries:</strong></p>
<select multiple="true" data-bind="options: availableCountries,
optionsText: 'countryName',
optionsCaption: 'Choose...',
selectedOptions: chosenCountries">
</select>
</form>
<main class="fifty last">
<p><strong>Country Info:</strong></p>
<p data-bind="visible: chosenCountries().length > 0, foreach: chosenCountries()" class="country-summary">
<span>
<strong data-bind="text: countryName"></strong>
<em>- Population:
<span data-bind="text: countryPopulation"></span>
</em>
</span>
</p>
</main>
<p style="clear:both">
<button>Check value</button>
</p>
CSS
body {
background: rgba(247, 243, 222, 0.9);
color: #777;
font: 16px Arial, Helvetica, sans-serif;
max-width: 100%;
margin: 0 auto;
padding: 1em 3em;
text-align: center;
}
a,
a:hover,
a:visited,
a:active,
a:focus,
h2 {
color: rgb(139, 116, 61);
}
button,
input,
select {
box-sizing: border-box;
border: 1px solid rgba(139, 116, 61, 0.9);
padding: 0.5em 1em;
width: 100%;
}
h1,
h2,
h3,
h4,
h5,
h6 {
margin: 0;
}
h2 {
font-size: 1.5em;
margin: 0;
}
h4 {
font-size: 1.2em;
}
main .country-summary {
font-size: 0.9em;
}
main .country-summary > span {
display: block;
margin: 0;
}
p {
text-align: center;
}
.fifty {
width: 48%;
float: left;
margin-top: 1em;
}
.fifty.last {
float: right;
}
button {
background: rgba(139, 116, 61, 0.9);
border-color: rgba(0, 0, 0, 0.15);
border-radius: 3px;
box-sizing: border-box;
color: #fff;
cursor: pointer;
height: 2em;
margin-top: 1em;
max-width: 50%;
outline: none;
text-transform: uppercase;
}
JavaScript
// Constructor for an object with two properties
var Country = function(name, population) {
this.countryName = name;
this.countryPopulation = population;
},
viewModel = function() {
var self = this;
self.availableCountries = ko.observableArray([
new Country("UK", "65,000,000"),
new Country("USA", "320,000,000"),
new Country("Sweden", "29,000,000")
]);
self.chosenCountries = ko.observableArray([]);
},
appliedVM = new viewModel();
ko.applyBindings(appliedVM);
$(document).ready(function() {
$("button").on("click", function() {
console.log(appliedVM.chosenCountries());
});
$("form").on("submit", function() {
return false;
});
});