Working with a list of checkboxes in knockoutjs

Viewed 27996

I'm trying to get my head around Knockout.js and I'm quite stuck when it comes to checkboxes.

Server side I'm populating a set of checkboxes with their corresponding values. Now, when any of the unchecked checkboxes are checked, I need to store it's value in a comma-seperated string. When they're unchecked, the value needs to be deleted from the string.

Have anyone got a hint on how to achieve this with knockoutjs?

I have the following code so far:

ViewModel:

$().ready(function() {
   function classPreValue(preValue)
   {
       return {
            preValue : ko.observable(preValue)
       } 
   }

   var editOfferViewModel = {
   maxNumOfVisitors : ko.observable(""),
   goals : ko.observable(""),
   description : ko.observable(""),
   contact : ko.observable(""),
   comments : ko.observable(""),
   classPreValues : ko.observableArray([]),
   addPreValue : function(element) {
      alert($(element).val());
      this.classPreValues.push(new classPreValue(element.val()));
   }
 };

 ko.applyBindings(editOfferViewModel);
});

And my checkboxes are populated with a foreach loop:

<input data-bind="checked: function() { editOfferViewModel.addPreValue(this) }"
       type="checkbox" checked="yes" value='@s'>
    @s
</input>

I try to pass the checkbox element as the parameter to my addPreValue() function, but nothing seems to happen when I check the checkbox?

Any help/hints on this is greatly appreciated!

2 Answers
Related