Saving a variable's value using Knockout loop within an HTML document

As a newcomer to KO, I have been utilizing the following code in my HTML file to print a specific value:

<!-- ko foreach: { data: JSON.parse($parent.options), as: 'option' } -->
    <!-- ko if: option.label === 'AAA' || option.label === 'BBB'  -->
        <dd class="values" data-bind="html: option.value"></dd>
    <!-- /ko -->    
<!-- /ko -->

This setup is functioning properly. However, I have a new requirement where I need to store all the values from the loop into a variable and output them after the loop just like we would do in PHP:

foreach($data as $key=> $index){
    if($key==0)
        $var = $index['value'];
    else
        $var .= ' '.$index['value'];    
}

echo $var

I am looking for a way to achieve the same result within KO's HTML file using the above mentioned KO loop structure.

Answer №1

To enhance functionality, consider creating 2 specializedcomputed properties as follows:

  • parsedOptions: extracts the parsed JSON data.
  • concatenatedValues: combines values into a string with space separation using map and join.

Next, iterate through the parsedOptions within a foreach loop. Then bind the concatenatedValues to a span.

const JSONstring = JSON.stringify([{ label: "AAA", value: 1 },{ label: "BBB", value: 2 },{ label: "CCC", value: 3 }]);

const viewModel = function() {  
  this.options = JSONstring;
  
  this.parsedOptions = ko.computed(() => {
    return JSON.parse(this.options)
  });
  
  this.concatenatedValues = ko.computed(() => {
    return this.parsedOptions().map(a => a.value).join(' ')
  });
}

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

<!-- ko foreach: { data: parsedOptions, as: 'option' } -->
    <!-- ko if: option.label === 'AAA' || option.label === 'BBB'  -->
        <dd class="values" data-bind="html: option.value"></dd>
    <!-- /ko -->
<!-- /ko -->

<br> All values:
<span data-bind="text: concatenatedValues"></span>

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

managing arrays in JavaScript with multiple tables

**I have successfully written code for calculating the sum of inputs in one table** $('#example122').on('input', '.calculate', function () { calculateTotal(); }); function calculateTotal() { var grandTotal = 0; $ ...

Adding Bootstrap to container-specific styling in SCSS

I am currently in the process of upgrading to the most recent version of reactstrap & Bootstrap. Previously, I had reactstrap in my package.json file and downloaded Bootstrap SCSS in my client/src/styles/bootstrap directory. Now, my updated package.json c ...

Tips on attaching a suffix icon to a material-ui-pickers input box

Here is a snippet of my code: <Box p={6}> <Grid container spacing={2}> <Grid item xs={6}> <TimePicker autoOk label={t('checkIn')} value={time1} onChange={handlecheckIn} clearable /> </Grid> < ...

What is the process for resolving the file paths of custom modules in node.js, whether they are absolute or relative?

require doesn't seem to recognize any path other than './parser1'. Despite placing both js files on the Desktop, attempting to run node my_parser.js always results in an error stating "Cannot find module" for relative paths like require(&apo ...

Unable to display JSON results in a tabular format

After successfully implementing the AJAX method in jQuery, I am able to receive a response. However, I am encountering difficulties when trying to display the arrays in a table format. success:function(resp){ var json =JSON.parse(JSON.stringif ...

Change the value of input on onClick event in React

Although this may seem simple, it is a little confusing to me. I'm having trouble understanding why the input value in the following case is not being reset. handleReset() { this.setState({ data: "" }); } <button onClick={this.handleReset}>R ...

Is there a way to identify if the parent page has completed loading while within an iframe?

Is there a way to detect properties or events within the iframe that can help determine this? The src of the iframe and the parent page belong to different domains. ...

Unlocking the power of variables in Next.js inline sass styles

Is there a way to utilize SASS variables in inline styles? export default function (): JSX.Element { return ( <MainLayout title={title} robots={false}> <nav> <a href="href">Title</a> ...

A guide on switching the status of various inputs in a table based on the selection of a radio button

In the scenario below, let's consider the following HTML structure: <tr> <td> <label for="c1_testRdio">Have you taken any tests in this class?:</label> <br> <label>Yes<input type="rad ...

``The problem of cross-origin resource sharing (CORS)

Encountering a CORS error when sending the request, although it works fine in Postman Error Message: The fetch request to (cloud function url) from my web app origin is being blocked by CORS policy: No 'Access-Control-Allow-Origin' header is p ...

Difficulty encountered while setting up jQuery slider

I am struggling to set up a jquery slider (flexslider) It seems like I am overlooking something very fundamental, but for some reason I just can't figure it out. Any assistance would be greatly appreciated. Please check out the link to the test site ...

The module 'nodemailer' could not be located

Currently working with the Zapier Code tool, my goal is to send an email with Trello parameters. I've been using JavaScript encoding in combination with node.js for this task. However, every time I attempt to locate the 'nodemailer' module, ...

"Creating varying lengths of time with useSpring: A Step-by-Step Guide

Is there a way for my component to have an animation that fully displays in 0.3s when my mouse enters, but disappears in 0.1s when my mouse leaves? Currently, with useSpring, I can only define one duration for both scenarios. How can I set different dura ...

Tips on finding the key associated with a specific value

When a form is submitted, one of the fields being sent is an ID number instead of the name for easier processing by the server. For example: HTML dropdown select <select ng-model="myColor" class="form-control" ng-options = "color.ID as color.color ...

Unable to load JQuery from a div element

My goal is to create a standard .html file containing the navigation, footer, and other elements that will be used across multiple pages for a small site I'm building. I want to keep it simple and avoid using php or other programming languages. I&apo ...

executing a hook within _app.tsx in Next.js

The issue I'm facing involves the rendering of a hook that helps determine if my components are within the screen's view to trigger animations. This hook is executed in _app.tsx, however, it doesn't run when switching to another page. Oddly ...

Potential issue with Jhipster: loading of data could be experiencing delays

I've encountered an issue with getting my chart to display properly. I am working on creating a chart using ng2-charts, where I retrieve data from a service and then display it on the chart. The problem arises when the data is not correctly displayed ...

Automatically select and pre-fill a list item based on its value using jQuery

I'm a beginner in JQuery. In my application I have the following: Here is my HTML code: <ul id="list"> <li> <a class="selected" value="0" href="#" id="sel">ALL</a> </li> <li> <a hre ...

Ensure that an input field on the PHP form is required

Currently working on a form with multiple input fields. I'm wondering if there's a way to prevent the form from being submitted to the server if a specific field is left empty. I'd like to use a JavaScript pop-up box to notify the user inst ...

Having trouble fixing the '@material-ui/lab' error while working with the newest React update?

My goal is to set up a global alert by following this method: Check out the Sandbox Demo Yet, I encounter an issue with the following error message: ERROR in ./src/components/snackbar/Alert.js 5:0-82 Module not found: Error: Can't resolve '@m ...