vendredi 25 juin 2021

knockout - header checkbox stays unchecked in table header when clicked

I am new to knockout and I am stuck at a problem for last couple of days - I am sure it is something silly but cant figure out. Any help will be appreciate. I am trying to select and deselect all rows in a table based on the header check box column. The SelectAll function works and selects/unselects all rows in table but the header remains unckecked?

    <tr>    
        <th><input type="checkbox" data-bind="click: selectAll, checked: AllChecked"></th>
        <th>@Html.Vocab("Document")</th>
        <th>@Html.Vocab("Notes")</th>
        <th>@Html.Vocab("Created")</th>
    </tr> 

    <tbody data-bind="foreach: DocumentRows">
        <tr >
            <td><input type="checkbox" data-bind="checked: IsSelected"></td>   
            <td><data-bind="text: Notes"></td>               
        </tr>
    </tbody>

And here is the script:

 //Document
    class Document {
        Id: KnockoutObservable<number>;
        Notes: KnockoutObservable<string>;       
        IsSelected: KnockoutObservable<boolean>;
        constructor(data?) {
            this.Id = ko.observable(0);
            this.Notes = ko.observable("").extend({ defaultValue: "" });            
            this.IsSelected = ko.observable(false);
            if (data != null) {
                ko.mapping.fromJS(data, {}, this);
            }            
        }      
        
    };


//DocumentS VIEW MODEL
  class DocumentsViewModel {
    DocumentRows: KnockoutObservableArray<Document>;        
    IsAnySelected: KnockoutObservable<boolean>;//used for delete button
    constructor(params) {
       this.DocumentRows = ko.observableArray([]);
       this.selectedIds = ko.observableArray([]);
    }
    
    InitComputed = () => {
       this.IsAnySelected = ko.pureComputed(() => {
                    var isChecked = false;
                    ko.utils.arrayForEach(this.DocumentRows(), function (item) {
                        if (item.IsSelected()) {
                             isChecked = true;
                         }
                     });
                    return isChecked;
                });
    }
    selectAll = (): void => {
                
                if (this.selectedIds().length > 0) {
                    this.selectedIds.removeAll();
                    ko.utils.arrayForEach(this.DocumentRows(), function (item) {
                        item.IsSelected(false);
                    });
                 
                } else {
                    ko.utils.arrayPushAll(this.selectedIds(), this.DocumentRows())
                    ko.utils.arrayForEach(this.DocumentRows(), function (item) {
                        item.IsSelected(true);
                    });
                  
                }
              
            }
    }



Aucun commentaire:

Enregistrer un commentaire