Search code examples
htmlknockout.jshtml-tableknockout-mvc

Knockout JS inside table collapse two columns depending on visibility


I'm pretty new in Knockout JS binding and I have this table which is supposed to be a row with a single column with the button if the Confirmed text is empty and two separate columns in other way.

Here is what I've tried so far,

<table class="table" id="Mytable" style="table-layout: fixed;">
       <tbody data-bind="foreach: info">
              <tr>
                 <td style="vertical-align:middle;">
                     <button type="button" class="btn2 btn-default" data-bind="click:$root.getClick, trimText:shortName, trimTextLength: 5, css: Confirmed == '' ? colspan='2' : ''">22</button>
                 </td>
                 <td style="vertical-align:middle">
                      <span style="color:green" data-bind="text: Confirmed, visible: Confirmed != ''">10</span>
                 </td>
              </tr>
        </tbody>
</table>

but it seems that it doesn't display the info correctly and I don't know what am I doing wrong.

Please be gentle with me, I'm trying to learn from mistakes.


Solution

  • colspan is an attribute, which you set using the attr binding:

     data-bind="attr: { 'colspan': Confirmed() ? 1 : 2 }"
    

    In your specific case, I'd use a virtual if binding to switch between the two cases:

    <table>
      <tbody data-bind="foreach: info">
        <tr>
          <!-- ko if: Confirmed -->
          <td colspan="2">
            <button type="button" 
                    data-bind="click:$root.getClick, trimText:shortName, trimTextLength: 5">22</button>
          </td>
          <!-- /ko -->
          <!-- ko ifnot: Confirmed -->
          <td></td>
          <td>
            <span data-bind="text: Confirmed"></span>
          </td>
          <!-- /ko -->
        </tr>
      </tbody>
    </table>