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

Alter the color scheme of Fancybox's background

I am looking to create a transparent background color for Fancybox. The typical method involves using ".fancybox-skin" in CSS, however this will affect all fancyboxes and I require it to be unique. Therefore, the setting must be sent with wrapCSS. Fancyb ...

Display text when hovered over or clicked to insert into an HTML table

I have an HTML table connected with a component field gameArray and I need it to: Show 'H' when the user's cursor hovers over TD (:hover) and the corresponding field in gameArray is an empty string, Fill the gameArray field after a click. ...

"Key challenges arise when attempting to execute the node app.js script through the terminal due to various middleware compatibility

I'm a beginner with node.js and I've encountered an issue while trying to run my node app.js file after incorporating a new file named projects.js which contains the following JS code: exports.viewProject = function(req, res){ res.render(" ...

Having trouble getting Tinymce to appear on the screen

I am currently attempting to install TinyMCE for use with my text editor in order to provide the user with a text box similar to the one on Stack Overflow. However, I am encountering an issue where it is not displaying as expected. In the header of my ind ...

Ways to incorporate ng-app into an HTML element when HTML access is limited

In my current project, I am using Angular.js within a template system. The challenge I am facing is that I need to add ng-app to the html element, but I do not have direct access to do this on the page itself. Initially, my page structure looks like this: ...

The issue of the highlighted row not disappearing persists even after clicking on the adjacent table row

When selecting the gear icon for the menu option in a table row, I would like the background to turn yellow. I attempted the following code to highlight the table row: var view = Core.view.Menu.create({ model: model, menuContext: { ibmm: ibmm }, ...

How to choose elements using jQuery according to their CSS properties?

Seeking a solution to a unique challenge I've encountered. The website I frequent has found a way to bypass my uBlock extension by using a script that generates random element classes, such as: <div class="lcelqilne1471483619510ttupv"></div& ...

Tips for substituting @media (max-width) with Stylish or Greasemonkey?

I am encountering an issue when trying to access this specific website on my desktop browser. The site has a responsive/fluid design that switches to displaying a mobile menu button instead of a horizontal nav-bar when the browser width is less than 990px. ...

What value does a variable have by default when assigned to the ko.observable() function?

I am in the process of learning KnockoutJS and I have implemented code for folder navigation in a webmail client. In the view code, there is a comparison being made to check if the reference variable $data and $root.chosenFolderId() point to the same memor ...

Is there a way to determine if a table cell contains overflowing text compared to another cell?

Is there a way to detect if the content of the fourth td overflows from the second td? I am looking for a method to determine which td has overflowed text and identify which td's text is overflowing. What approach can be used to determine which td i ...

Creating stunning visuals with the power of SVG

I need to create a graphics editor similar to Paint using SVG for a school project. I have JavaScript code for drawing shapes like circles and lines, but when I try to add them to an onClick function for a button, it doesn't seem to be working. funct ...

What function does the sx prop serve in Material UI?

<Container style={{ margin: "10px" }}> <Article post={post} setCurrentId={setCurrentId} /> </Container> <Container sx={{ margin: "10px" }}> <Article post={post} setCurrentId={setCurrentId} /> </Cont ...

Using CSS, eliminate the drop-down menu from the main navigation on Squarespace

While working on my Squarespace website, I've been impressed with how the FAQ page/questions are structured. However, a drawback is that it creates a clunky drop-down menu when hovering over the FAQ tab in the main navigation. You can see an example ...

Wordpress articles refuse to appear side by side

I've been at it for hours now, trying to solve this issue with no luck. I have a Wordpress loop on my homepage that displays post thumbnails vertically, but I want them to appear in sets of three images before starting a new line. Here's the cod ...

Two-toned diagonal design featuring a lone character

I'm searching for a unique design featuring the letter "d" in two colors, arranged diagonally without any gradient effects. Here is the CSS code I am currently using: .gradient_text_class { font-size: 72px; background-image: linear-gradient(50de ...

Is there a space added after applying overflow:hidden to a div?

.d1 { height: 10px; } .dd { display: inline-block; overflow: hidden; } .dd1 { display: inline-block; } <div class="d1"> <div class="dd"></div> <div class="dd1"></div> </div> To adjust the layout so that th ...

Exploring the Differences in CSS Styling between Web and Mobile Platforms

Recently, I launched my new website and encountered a peculiar issue. Upon clicking on Pickup Date & Time, a bootstrap datepicker pops up like it should. However, the problem arises when viewing the website on mobile devices - the datepicker appears offsc ...

`Enhancing the appearance of code in PHP`

I'm struggling with customizing the data pulled from the database. Can anyone provide assistance? I attempted to define $style within the while loop and assign it to $questions, but nothing is displaying on the webpage. While I have some familiarity w ...

"Enhancing User Experience with AngularJS by Dynamically Modifying and Refresh

I'm currently attempting to dynamically add HTML elements using JavaScript with a directive: document.getElementsByClassName("day-grid")[0].innerHTML = "<div ng-uc-day-event></div>"; or var ele = document.createElement("div"); ele.setAttr ...

Show one line of text at a time with a pause in between each one

On my HTML page, I am looking to showcase text lines in succession with a delay. The unique condition is that when the second line appears, the color of the first line should change. Then, as the third line emerges, the color of the second line should also ...