Reputation: 1670
I am trying to learn KO and when I write this is in a html, the input text box doesn't have the value on the load. Can some one help.
<html>
<head>
<script src="C:\Data\Visual Studio 2013\Projects\WebApplication3\KObasics\Scripts\knockout-3.4.2.debug.js" type="text/javascript">
</script>
<script type="text/javascript">
// This is a simple *viewmodel* - JavaScript that defines the data and behavior of your UI
function AppViewModel() {
this.firstName = "Bert";
this.lastName = "Bertington";
}
// Activates knockout.js
ko.applyBindings(new AppViewModel());
</script>
</head>
<body>
<p>Use this area to provide additional information.</p>
<input data-bind="value:firstName"/>
<p data-bind="text:firstName"></p>
</body>
</html>
Upvotes: 1
Views: 40
Reputation: 2350
Your html and javascript looks ok, as it is working fine below.
// This is a simple *viewmodel* - JavaScript that defines the data and behavior of your UI
function AppViewModel() {
this.firstName = "Bert";
this.lastName = "Bertington";
}
// Activates knockout.js
ko.applyBindings(new AppViewModel());
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>
<p>Use this area to provide additional information.</p>
<input data-bind="value:firstName"/>
<p data-bind="text:firstName"></p>
You just need to move the <script>
tag to the end of <body>
element before the closing tag (</body>
). To make sure the DOM element are rendered before those are bind to the knockout model. It'll be like this:
<html>
<head>
<script src="C:\Data\Visual Studio 2013\Projects\WebApplication3\KObasics\Scripts\knockout-3.4.2.debug.js" type="text/javascript">
</script>
</head>
<body>
<p>Use this area to provide additional information.</p>
<input data-bind="value:firstName"/>
<p data-bind="text:firstName"></p>
</body>
<script type="text/javascript">
// This is a simple *viewmodel* - JavaScript that defines the data and behavior of your UI
function AppViewModel() {
this.firstName = "Bert";
this.lastName = "Bertington";
}
// Activates knockout.js
ko.applyBindings(new AppViewModel());
</script>
</html>
Upvotes: 1