knockout js按钮单击选中所有复选框

时间:2016-10-27 11:55:09

标签: javascript jquery knockout.js knockout-2.0

我正在使用Knockout js进行绑定,我是带有复选框的数据绑定列表,我正在获取并绑定到列表项的数据,包括所有项目的复选框,现在我需要创建新的按钮名称“select-all”和当我点击该按钮时,我需要选中所有复选框,我需要从所选复选框中获取所有数据如何实现此需求帮助..

<div>
<input type="button" value="Select-All" data-bind="click:SelectAll" />
</div>
<div  id="List" data-bind="foreach:items">
<ul>
<li>
<span data-bind="text:userId" style="display:none"></span>
<span style="margin-top: 10px;font-size: 22px;font-weight: bold;padding-left:0px;" data-bind="text:username"></span>
<input  type="checkbox" data-bind="value:userId(),click:$root.toggle" />                   
</li>
</ul>
</div>

 //ViewModel
function userViewModel()
 var self=this;
     {
    function userList(userId, userName)
     {
      var self=this;
     self.userID=ko.observable(userId);
     self.userName=ko.observable(userName);
     self.Selected = ko.observable(false);
     }
   self.toggleAssociation = function (item) {
     //here i am getting the individual selected checkbox Item 
   }

 //This part is not working 
  self.SelectAll = function() {
  console.log("in")
 self.items().forEach(function(item) {
    item.Selected(true);
});
  };

   self.items = ko.observableArray();
     self.add = function (userId, userName,){
     self.items.push(new FriendsContact(userId, userName)
   }
};

 //Page Load  
 $(function () {
var viewModel = new userViewModel();
ko.applyBindings(viewModel);

 //Get the data from database//
 $.ajax({
    type: "GET",
    dataType: "json",
    contentType: 'application/json; charset=utf-8',      
    url: baseUrl + 'xxx/xxx/xxxxx',
    success: function (data) { 
            $.each(data, function (key, value) {
                viewModel.add(value.userId, value.userName)
            });
    }
})
});

3 个答案:

答案 0 :(得分:1)

在功能范围开始放置{之前,您无法定义变量。下面的减速是错误的

function userViewModel()
  var self=this;
     {

根据我从您的代码中看到的内容,我将向您展示如何处理此类问题。

示例:https://jsfiddle.net/kyr6w2x3/103/

<强> HTML:

 <div>
      <input type="button" value="Select-All" data-bind="click:SelectAll,visible:ShowSelectAllBtn" />
      <input type="button" value="UnSelect-All" data-bind="click:UnSelectAll,visible:ShowSelectAllBtn() == 0" />
    </div>
    <div>
      <input type="button" value="Add" data-bind="click:add" />
    </div>
    <div  id="List" data-bind="foreach:items">
      <ul>
        <li>
          <span data-bind="text:userId"></span>
          <span style="margin-top: 10px;font-size: 22px;font-weight: bold;padding-left:0px;" data-bind="text:userName"></span>
          <input  type="checkbox" data-bind="checked:Selected" />                   
        </li>
      </ul>
    </div>

<强> JS:

var data = [{userId:1 , userName : "UserName1"},{userId:2 , userName : "UserName2"}];

function userViewModel(){
   var self = this;
   self.items = ko.observableArray();
   self.ShowSelectAllBtn = ko.observable(true);
   self.loadData = function (){
     // here you have your ajax 
     //maping fake data assuming it is inside the ajax's success
     self.items($.map(data, function (item) {
       return new userItemViewModel(item);
     }));
   }
  self.SelectAll = function() {
    self.ShowSelectAllBtn(false);
    ko.utils.arrayForEach(self.items(), function (item) {
      item.Selected(true);
    });
  };
  self.UnSelectAll = function() {
    self.ShowSelectAllBtn(true);
    ko.utils.arrayForEach(self.items(), function (item) {
      item.Selected(false);
    });
  };
  var i = 2;
  self.add = function (userId, userName){
    // creating a fake json object with a userId and a userName
    userId = i++;
    userName = "userName" + i;
    obj = {userId:userId , userName : userName} ;
    self.items.push(new userItemViewModel(obj) );
  }
};

var userItemViewModel = function (data){
    var self = this;
    self.userId = ko.observable(data.userId);
    self.userName = ko.observable(data.userName);
    self.Selected = ko.observable(false);
    self.Selected.subscribe(function(newValue){
     //individual selected checkbox 
       console.log(newValue);
       console.log(self.userId());
       console.log(self.userName());
    }, self);
}

var viewModel = new userViewModel();
ko.applyBindings(viewModel);
// Load data
viewModel.loadData();

答案 1 :(得分:0)

您需要为userViewModel添加新方法:

self.SelectAll = function() {
    self.items().forEach(function(item) {
        item.Selected(true);
    });
};

答案 2 :(得分:0)

@ haim770是正确的,你必须循环遍历元素并设置item.Selected(true)。现在的问题是:

<input  type="checkbox" data-bind="value:userId(),click:$root.toggle" />
  • 首先,复选框已映射到userId而不是Selected
  • 其次,复选框没有值绑定。它具有checked绑定。所以它应该是:

<input type="checkbox" data-bind="checked:$data.Selected,click:$root.toggle" />

此外,您应该避免使用$root。您可以将其替换为$parent.toggle

Working Fiddle