m sid
m sid

Reputation: 1

How to render a checked checkbox using knockout js when page is loaded

I've just started playing around with Knockout.js, and it seems really cool. What I have is a table. I am displaying 10 rows in this table with the first column being checkbox. When the page is loaded i want to render the page so that first checkbox is checked by default. My code so far is as below.

               <tbody data-bind="foreach: ExistingTablesInfo">
                <tr>
                    <td class="input-group">
                        <input type="checkbox" />
                    </td>
                    <td data-bind="text: aaa"></td>
                    <td data-bind="text: bbb"></td>
                    <td data-bind="text: ccc"></td>
                    <td data-bind="text: moment(ddd).format('L')"></td>
                    <td data-bind="text: moment(eee).format('L')"></td>
                    <td data-bind="text: moment(fff).format('L')"></td>
                    <td data-bind="text: ggg"></td>
                    <td data-bind="text: hhh"></td>
                </tr>
            </tbody>


Upvotes: 0

Views: 360

Answers (1)

Amit Bhoyar
Amit Bhoyar

Reputation: 1057

You need to have an observable variable in ExistingTablesInfo array. If you have existing data you can add one extra parameter using map() but at last structure should look like below. Also use checked binding to bind that observable, set it to true to checked and false to unchecked. Its 2 ways binding so values of property will change if you change check box state.

function viewModel() {
  var self = this;
  
  self.ExistingTablesInfo = ko.observableArray([
      {isSelected : ko.observable(true), aaa:"aaa1", bbb:"bbb", ccc:"ccc"},
      {isSelected : ko.observable(true), aaa:"aaa2", bbb:"bbb", ccc:"ccc"},
      {isSelected : ko.observable(true), aaa:"aaa3", bbb:"bbb", ccc:"ccc"},
      {isSelected : ko.observable(false), aaa:"aaa4", bbb:"bbb", ccc:"ccc"},
      {isSelected : ko.observable(true), aaa:"aaa5", bbb:"bbb", ccc:"ccc"},
      {isSelected : ko.observable(true), aaa:"aaa6", bbb:"bbb", ccc:"ccc"}
   ])
}

ko.applyBindings(new viewModel());
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
<table>
  <tr>
    <th>col1</th>
    <th>col2</th>
    <th>col3</th>
    <th>col4</th>
  </tr>
  <tbody data-bind="foreach: ExistingTablesInfo">
    <tr>
      <td class="input-group">
        <input type="checkbox" data-bind="checked:isSelected" />
      </td>
      <td data-bind="text: aaa"></td>
      <td data-bind="text: bbb"></td>
      <td data-bind="text: ccc"></td>
    </tr>
  </tbody>

</table>

Upvotes: 1

Related Questions