CheckBox not checked in Knockoutjs

I use a checkbox with a function inside data-bind , but I cannot check to check this box.

View:

 <input type="checkbox" data-bind="click: function(){ f('hello parameter'); }">Click me 

Show model:

 var VM = function () { this.f = function (param) { alert(param); // here i am getting 'hello parameter' return true; } } ko.applyBindings(new VM()); 

Here is my fiddle

+5
source share
2 answers

By default, the click binding prevents the default response of the click based on the assumption that the JavaScript event handler for JavaScript will handle everything. You need to return β€œtrue” to get the default behavior anyway that you make from your f() function, but not for the shell inside the data-bind :

 <input type="checkbox" data-bind="click: function() { f('hello parameter'); }"> 

it should be

 <input type="checkbox" data-bind="click: function() { return f('hello parameter'); }"> 
+12
source

Without context around the code, it’s not clear how you are going to use this control. With a checkbox, you usually use the checked binding, which is bound to a logical observable:

A validated binding associates a controlled form element β€” that is, a check box () or a switch () β€”to a property in your view model.

So another way of writing using checked bindings:

Code example:

 var VM = function () { var self = this; self.myCheck = ko.observable(false); self.myCheck.subscribe(function () { alert('checked value = ' + self.myCheck()); }); } ko.applyBindings(new VM()); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script> <div> <input type="checkbox" data-bind="checked: myCheck" /> Click me </div> 

In this example, an observable is observed that tracks the value of the flag: self.myCheck . Therefore, when the checkbox is checked / self.myCheck() , self.myCheck() will be set to true / false.

In order to provide some output or run some code when the value changes, I subscribed to the observable, which basically means that every time the value of the observable changes, a warning will be displayed (or some code you place there).

Demo On JS Fiddle

+5
source

Source: https://habr.com/ru/post/1204620/


All Articles