I am new about KnockOutJs and I have this problem. This is my simple form and I would execute the function Login only when I click on the button. However, the function is executed when page loads without the user clicking it. How can I fix it?
$().ready(function() {
function ViewModel() {
var self = this;
self.username = ko.observable();
self.password = ko.observable();
self.Login = function() {
console.log('do login');
};
}
ko.applyBindings(new ViewModel());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>
<div class="form-group">
<input type="text" id="username" name="username" data-bind="value:username" placeholder="User Name" />
</div>
<div class="form-group">
<input type="password" id="password" name="password" data-bind="value:password" placeholder="Password" />
</div>
<button type="button" id="btnlogin" data-bind="click:Login()">login</button>
()
in yourclick
binding: you reference the method, not execute it. I.e.:data-bind="click: Login"
– user3297291Login
as soon as the DOM elements are created...hence the alert event without clicking on the button... – gkb