Working with a list of checkboxes in knockoutjs

后端 未结 2 1063
南方客
南方客 2020-12-05 20:26

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 correspond

2条回答
  •  庸人自扰
    2020-12-05 21:09

    Why isn't there a Mutually exclusive checkboxes example Online somewhere

    Since this link came up first whilst I was searching for mutually exclusive checkboxes I will share my answer here. I was banging my head against the wall with all my attempts. By the way, when you handle the click event in a binding in-line knockoutjs it seems to disconnect the bindings(maybe only because I tried to call my resetIllnesses function as defined below) even if you return true from the function. Maybe there is a better way but until then follow my lead.

    Here is the type I needed to bind.

    var IllnessType = function (name,title) {
        this.Title = ko.observable(title);
        this.Name = ko.observable(name);
        this.IsSelected = ko.observable(false);
    };
    

    The array to bind with.

    model.IllnessTypes = ko.observableArray(
        [new IllnessType('IsSkinDisorder', 'Skin Disorder'),
            new IllnessType('IsRespiratoryProblem', 'Respiratory Problem'),
            new IllnessType('IsPoisoning', 'Poisoning'),
            new IllnessType('IsHearingLoss', 'Hearing Loss'),
            new IllnessType('IsOtherIllness', 'All Other Illness')]
    );
    

    The reset illness function to clear them all.

    model.resetIllnesses = function () {
        ko.utils.arrayForEach(model.IllnessTypes(), function (type) {
            type.IsSelected(false);
        });
    };
    

    The markup

    This just doesn't work

    If you have been struggling with trying to call the resetIllness function as I below, you will feel my pain.

    
    

    you have been sharing my pain. Well, it works! when you call it from following example. Notice that there is a class that I added above so that I can add the click function.

    The script that makes all your problems go away.

    
    

    Send info to the server

    Also, in my case I had to send the information up to the server differently than the default html format so I changed the inputs a little.

    
    
    

提交回复
热议问题