0

With the following code how do I set it so that only 3 tables can be present per line within the outer table. Please and thankyou!!!!!

Clarification: my inner table represents a cake, I want to find a way to display only 3 cakes per row on the screen before starting a new row.

    E.g.   cake |  cake |   Cake 
              Cake |  cake |  cake 
              Cake |  cake  |  cake. 

    <div>
    <table>
    <tbody>
        <tr data-bind="foreach: cakes">
            <td>
                <table style="border: solid red 1px;">
                    <tr><td align="center"><p class="cake-name" data-bind="text: name"></p></td></tr>
                    <tr><td><img data-bind="attr: { src:  image}" width="300" height="200" /></td></tr>
                    <tr><td width="300"><p class="cake-description" data-bind="text: description"></p></td></tr>
                    <tr><td><p data-bind="text: price"></p></td></tr>
                    <tr><td><button type="button" class="del btn btn-xs btn-danger" data-bind="click: $root.showDeleteModal.bind($root)">Delete</button></td></tr>
                </table>
            </td>
        </tr>
    </tbody>
</table>
</div>
Daniel Brown
  • 63
  • 1
  • 5
  • can you post it in a jsfiddle? And i am not understand your question fully. Can you provide example. – vicnoob Jan 11 '18 at 04:59
  • https://stackoverflow.com/questions/40564995/take-three-elements-at-a-time-from-array – Roy J Jan 11 '18 at 22:03

1 Answers1

0

If I understand correctly you can see the top three items in cakes by simply changing your data bind to

foreach: cakes().slice(0, 3)

Edit: I guess I didn't understand the question. I've updated my answer to show how you can use $index() inside a knockout foreach loop to find your position and insert a line break every so often. In this case, every 3rd item.

function ViewModel() {
  var self = this;

  self.Cakes = ko.observableArray(['Vanilla', 'Chocolate', 'Strawberry', 'Almond', 'Ice Cream', 'Birthday', 'German Chocolate'])

}

ko.applyBindings(new ViewModel())
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
<div data-bind="foreach: Cakes">
  <span data-bind="text: $data"></span>
  <span data-bind="if: $index() % 3 == 2">
  <br>
  </span>

</div>
John Pavek
  • 2,595
  • 3
  • 15
  • 33
  • That would work for that scenario. But I’m actually wanting it to loop through all the cakes, display 3 on the first row then make a new row then display the next 3 and so on till all have been displayed. But just 3 per row. – Daniel Brown Jan 11 '18 at 18:07
  • @DanielBrown I've updated my answer, I hope I understood the question correctly. – John Pavek Jan 13 '18 at 03:42
  • 1
    After a little modification using that edited code you provided @JohnPavek it now works. Thank You! – Daniel Brown Jan 13 '18 at 20:46