Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checkbox binding in knockout not working on trigger event

The checkbox data-binding value is not changing when i try to trigger the click event of checkbox.

I have created a jsfiddle, when i click the button i expect the value bind to change but not.

http://jsfiddle.net/2T9QZ/13/

Any help?

like image 495
HashCoder Avatar asked Oct 09 '22 20:10

HashCoder


1 Answers

Calling trigger("click") in jQuery simply triggers your "click" event handler(s). It doesn't actually cause a click (and thereby a change of the checked state) on the checkbox - the only time it does something like that is in the case where the element has a function property named the same as the event (e.g. form.submit() - but there's no checkbox.click()).

But since you're using knockout, you might as well do:

var viewModel = {
    IsSelected: ko.observable(false) // Initially false
};

ko.applyBindings(viewModel);


$('#buttonInput').click(function(){
    viewModel.IsSelected(true); // <-------
    // Or, in order to toggle:
    // viewModel.IsSelected(!viewModel.IsSelected());
});

That's pretty much the point of using knockout in the first place. Make your changes on the view model, not the view. Since the checkbox's checked property is data bound to IsSelected, changing IsSelected will change the checked property of the checkbox.

like image 56
JimmiTh Avatar answered Oct 13 '22 12:10

JimmiTh