Organizing knockout data outcomes into two separate columns

Is there a way to split up this code into two columns using Knockout and HTML? I can do it easily in CSS, but the goal is to divide the results into segments 1-5 and 6-9. Here is the code snippet. Also attached is a screenshot for reference. Thank youhttps://i.stack.imgur.com/VgPpz.png

         <div class="item summary">
              <h3> <?=l(479)?> </h3>
                <div data-bind="foreach:$data.summary">
                  <div>
                   <span data-bind="text:$data.sequence + '.'"></span>
                    <span data-bind="text:$data.label + ':'"></span>
                    <span data-bind="text:$data.value"></span>
                  </div>
              </div>
           </div>

Answer №1

If you don't plan on changing the length, one approach is to duplicate the markup for each block and incorporate a slice() method. While not the most elegant solution, it's likely the simplest.

<!-- ko if: summary && summary.length > 0 -->
    <div data-bind="foreach: $data.summary.slice(0,5)">
        ...
    <div data-bind="foreach: $data.summary.slice(5)">
        ...
<!-- /ko -->

For a more dynamic option, consider creating a computed function that divides your array into multiple sections and use nested foreach loops instead:

function viewModel(){
    var self = this;
    this.summary = [
      new Summary(1),
      new Summary(2),
      new Summary(3),
      new Summary(4),
      new Summary(5),
    ];
    
    this.summaryBlocks = ko.computed(function(){
      if(self.summary && self.summary.length > 0){
      var size = self.summary.length / 2;
        return [
          self.summary.slice(0,size), 
          self.summary.slice(size)
        ];
      }else{
        return [];
      }
    });
}

function Summary(val){
    this.sequence = 'sequence';
    this.label = 'label';
    this.value = val;    
}

ko.applyBindings(new viewModel());
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>

<div class="item summary">
  <h3> <?=l(479)?> </h3>
  <div data-bind="foreach: summaryBlocks">
    <div style="display:inline-block; vertical-align:top;" data-bind="foreach:$data">
      <div>
        <span data-bind="text:$data.sequence + '.'"></span>
        <span data-bind="text:$data.label + ':'"></span>
        <span data-bind="text:$data.value"></span>
      </div>
    </div>
  </div>
</div>

EDIT: Here's another code snippet to handle a variable number of columns

function viewModel() {
  var self = this;

  this.columns = ko.observable(1);
  this.summary = [new Summary(1), new Summary(2), new Summary(3), new Summary(4), new Summary(5), new Summary(6), new Summary(7), new Summary(8), new Summary(9)];

  this.summaryBlocks = ko.pureComputed(function() {
    var result = [];
    for (var i = 0; i < self.columns(); i++) result.push([]);

    if (self.summary && self.summary.length > 0) {
      for (var i = 0; i < self.summary.length; i++) {
        var col = i % self.columns();
        result[col].push(self.summary[i]);
      }
    }
    return result;
  });
}

function Summary(val) {
  this.sequence = 'sequence';
  this.label = 'label';
  this.value = val;
}

ko.applyBindings(new viewModel());
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>

columns: <span data-bind="text: columns"></span>
<br/><input type="range" min=1 max=5 data-bind="value: columns" />

<div class="item summary">
  <div data-bind="foreach: summaryBlocks">
    <div style="display:inline-block; vertical-align:top;" data-bind="foreach:$data">
      <div style="border: 1px dashed blue;">
        <span data-bind="text:'item ' + value"></span>
      </div>
    </div>
  </div>
</div>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tips for repairing damaged HTML in React employ are:- Identify the issues

I've encountered a situation where I have HTML stored as a string. After subsetting the code, I end up with something like this: <div>loremlalal..<p>dsdM</p> - that's all How can I efficiently parse this HTML to get the correct ...

Using jQuery in Yii: Detecting when a radio button loses its checked state

Here is the code regarding the issue at hand: <script> $(function(){ $('#widgetId-form input[name="valueType"]').change(function(){ if ($(this).is(":checked")) { console.log("enabling "+$(this).data("class") ...

Displaying a pop-up window upon clicking on an item in the list view

After creating a list where clicking an item triggers a popup, issues arose when testing on small mobile screens. Many users found themselves accidentally tapping buttons in the popup while trying to view it. What is the most effective way to temporarily ...

Animating jQuery Counter with Changing Background Color

I've implemented a Counter that counts from 0 to a specified number, and it seems to be working perfectly. However, I want to add an animation where the background color of a div height animates upwards corresponding to the percentage of the counter. ...

Show a notification on the screen if the source of the iframe is blank

Is there a way to show a message "Please click on a match to get started" when no match link has been clicked? For example, when the iframe does not have an src attribute. My backend is built on Django. Below is the HTML code snippet: </form><b ...

What is the functionality of the CSS switch button?

I'm curious about how the cool turn on/off switch button actually works. Take a look at for reference. I'm interested in implementing a prevention check to confirm whether the user truly wants to switch the button. Here's a snippet of the ...

Is there a way to stop Bootstrap from automatically bolding the font?

When testing this simple example without the bootstrap link, everything seems to be working correctly: Hovering over any word changes its color to red, and when hovering away it returns to black. But as soon as the bootstrap link is included, the text bec ...

Scrolling to does not function properly with Material UI tabs

Looking for a solution to scroll to a specific div when clicking on a tab in Material UI Tabs using UseRef and ScrollTo. Check out the sandbox link here: https://codesandbox.io/s/exciting-sound-mrw2v Currently, when I click on Tab 2, I expect it to autom ...

Share on your Twitter feed

Currently seeking assistance in implementing a function on my website that allows users to post their individual posts to Twitter. For example: Message: "hello world" [twitter] By clicking on the twitter button, the message will be posted along with the p ...

Grouping and retrieving values from an array of JavaScript objects

I am looking to implement a groupBy function on the object array below based on the deptId. I want to then render this data on a web page using AngularJS as shown: Sample Object Array: var arr = [ {deptId: '12345', deptName: 'Marketin ...

Styling elements with inline-block in IE8

Although there are countless questions addressing this particular issue, allow me to provide more details: The Dilemma The situation is as follows: aside { display: inline-block; } section { display: inline-block; margin-left: 2em; } Here, the eleme ...

Aligning SVG clipping path using CSS

This problem has me stumped! I need to center the SVG clip within the surrounding div, just like in this example: http://jsfiddle.net/ztfdv9qh/ - Make sure to check the link because the SVG is quite long! <div class="svg-wrapper"> <div class ...

Steps on modifying the background of an element based on its location within the browser:

In the past, I've come across some impressive one-page websites with elements that would appear as you scroll. It seemed like they were created using just CSS. I think it might be achievable with the z-index and position properties? However, I can&ap ...

Troubleshooting border styling problems on an iPad for a table

I'm encountering a CSS issue specifically on iPad devices when rendering the HTML page. Oddly enough, everything appears fine on other browsers. The problem I'm facing is a small space between the cells in my tables as shown in this image: Stran ...

I desire to share the JSON information and receive the corresponding response data

<!DOCTYPE html> <html lang="en" dir="ltr"> <head> <meta charset="utf-8"> <title></title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> </head> ...

Having trouble with submitting an HTML form using JavaScript and PHP

My webpage has an HTML form that sends data to a PHP file for processing. One issue I'm facing is with a dynamically generated combo box that works fine when the page loads, but the selected value is not being passed when the form is submitted. The J ...

The most effective way to align text in a right-to-left language is by utilizing the text-align property with a

If the project is in a right-to-left language (such as Persian or Arabic), which method is preferable for setting text-align: right and direction: rtl? Option 1: Implement globally, for example: body * { direction: rtl; text-align: right; } ...

various image proportions in HTML

I have an image with a ratio of 16:9 that I want to use on my website. On one of the pages, I display a list of products with images having a ratio of 340x265. When a user clicks on an item in the list, it takes them to the product page where the same im ...

Clicking on a jQuery element will reveal a list of corresponding elements

I've retrieved a list of elements from the database and displayed them in a table with a button: <a href="#" class="hiden"></a> To show and hide advanced information contained within: <div class="object></div> Here is my jQ ...

Pressing the button will allow you to select and copy the text within the

I am looking to incorporate a mock-chat feature into my website. The concept is to type something on the website, then click a button next to it which will move the text to a frame above. I attempted this using a textarea and even found a code for selectin ...