Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When I click a checkbox in a knockout table row, the tr click event overrides the checkbox state change

I have a knockout table with checkboxes (for the example here, I've limited to one checkbox per row). when a checkbox is clicked, it should flip state (as you expect). however, I also have a click event and select event on the table row, which is conflicting with the checkboxes...

<table>
  <tbody data-bind="foreach: namespace.divResults.model">
    <tr data-bind="click: $root.selectItem, css: {selected: $root.isSelected($data)}">
      <td data-bind="text: Title"></td>
      <td data-bind="text: Surname"></td>
      <td data-bind="text: PostCode"></td>
      <td><input type="checkbox" data-bind="checked: Excluded, click: $root.toggleExcluded"></td>
      <td data-bind="text: Notes" style="display:none"></td>
    <tr>
  <tbody>
<table>
<div>
  <!-- ko with: $root.selectedItem -->
  <textarea data-bind="textInput:Notes"></textarea>
</div>

and the javascript:

(function(ns) {
  ns.divResults = null;
  var resultsViewModel = function() {
    var self = this;
    self.model = ko.observableArray();
    self.selectedItem = ko.observable();
    self.selectItem = function(row){ self.selectedItem(row); }
    self.isSelected = function (row) { return self.selectedItem() === row; }

    self.toggleExcluded = function() {
      return true;
    }
  }
}

I've tried using clickBubble event, but this blocks the actions of the click event on the table row, which works fine in any case. What I find is that clicking a row's checkbox changes its' state correctly, but then gets put back when the row click does its thing.

like image 810
JimFR Avatar asked Dec 06 '25 21:12

JimFR


1 Answers

I've used an actual checkbox, not sure if this is your requirements or not, anyway this is the column with the checkbox

<td>
    <input type="checkbox" data-bind="checked: Excluded"/>
</td>

Having a checkbox with checked binding deals with setting the Excluded flag and checking the checkbox at the same time. In the row click handler I return true to allow the event to propagate down to the checkbox, without this the checkbox won't work because the event won't propagate down to it

self.selectItem = function (row) {
     self.selectedItem(row);
     return true;
};

Here is a fiddle with a working example, I've added an input at the bottom that shows the status of Excluded as well

http://jsfiddle.net/5dk0hqnc/8/

like image 77
omerio Avatar answered Dec 08 '25 10:12

omerio



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!