Reputation: 43
How can I data-bind the colspan property of a table column with values using a ternary operator?
I tried something like this:
<td data-bind="attr: { colspan: condition() ? 3 : 4 }"> .... <td>
but it always taking the colspan as 4 (assuming the condition is always false)
My question is am I using the wrong syntax to bind the properties?
Any answers will be highly appreciated...Many thanks in advance.
Upvotes: 1
Views: 783
Reputation: 1707
This seems to work?
function ViewModel() {
var self = this;
self.isValid = ko.observable(true);
self.toggleColspan = function () {
console.log('changed to colspan ' + (self.isValid() ? 4 : 3));
return self.isValid(!self.isValid()); };
};
ko.applyBindings(new ViewModel());
table tr td {
background-color: gray;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.1/knockout-min.js"></script>
<a href="#" data-bind="click: toggleColspan">toggle</a>
<table>
<thead>
<tr>
<th>head1</th>
<th>head2</th>
<th>head3</th>
<th>head4</th>
</tr>
</thead>
<tbody>
<tr>
<td data-bind="attr: { colspan: $root.isValid() ? 3 : 4 }">body1</td>
</tr>
</tbody>
</table>
Upvotes: 1