This is a migrated thread and some comments may be shown as answers.

Help with binding checkbox Enabled to a function, not a variable

2 Answers 56 Views
MVVM
This is a migrated thread and some comments may be shown as answers.
Garrett
Top achievements
Rank 2
Garrett asked on 03 Jul 2012, 07:13 PM
I have a demo where I have a questionnaire question with some answers. The user is allowed to check up to 3 of the answers. When the user has checked 3 answers all checkboxes that are NOT checked have to be disabled.

The link for the demo I'm talking about is: http://jsfiddle.net/garrett55/ztpAf/

As you can see I am trying to use a function to disable some of the checkboxes but not others. This doesn't work and I think it has to do with the model not updating the view.

Anyone have an idea how to get something like this to work?

2 Answers, 1 is accepted

Sort by
0
Alexander Valchev
Telerik team
answered on 06 Jul 2012, 08:35 AM
Hello Garrett,

I noticed two issues with your code that most probably are the cause of the behaviour that you described. The if clause in the answerLimitReached function was not correct - when more than 3 check boxes were selected the function still returned true. The other issue is the MVVM context in the template - since the template is bound to the answers array, it will repaint (respectively apply the changes to all fields) when the answers array is changed. That is why to achieve your goal I would recommend modifying the data in the source array. For example:
checkboxChanged: function(e) {
    this.set('checkedBoxes', this.get('checkedBoxes') + (e.data.get('selected') ? 1 : -1));
    if (this.get('checkedBoxes') < 3) {
        return;
    } else {                  
        var data = this.get("answers");
        for (var i = 0; i < data.length; i++) {
            if(!data[i].selected) {
                data[i].set("isEnabled", false);
            }                   
        }
    }
}

For convenience I have updated your fiddle, please check the result and let me know if I missed something.

Regards,
Alexander Valchev
the Telerik team
Join us on our journey to create the world's most complete HTML 5 UI Framework - download Kendo UI now!
0
Garrett
Top achievements
Rank 2
answered on 06 Jul 2012, 01:18 PM
The solution was going to be my fallback plan if I was unable to bind to a function alone.

The only thing missing from the example is to enable all checkboxes when someone unchecks a checkbox after the limit is hit. Its an easy fix and here is a link to anyone who wants to look at it http://jsfiddle.net/garrett55/ztpAf/22/ 

Thanks for all the help. 
Tags
MVVM
Asked by
Garrett
Top achievements
Rank 2
Answers by
Alexander Valchev
Telerik team
Garrett
Top achievements
Rank 2
Share this question
or