How can I rearrange the output produced from a form by utilizing arrays?

The following code snippet generates the output:

Apple,Orange Sliced,Diced Option1 Option2 Option3 Option4 ,Option1 Option2 Option3 Option4

Desired output:

Apple Sliced Option1 Option2 Option3 Option4

Orange Diced Option1 Option2 Option3 Option4

The function addOptions() creates arrays from a form, and showOptions() replaces elements with the array data.

To achieve the desired output, what changes should be made in the following snippet?

var fruit
var prep
var saladsArr = [];
var salad = {
    "theFruit": []
    , "thePrep": []
    , "theOpt": []
};

// Code omitted for brevity

function resetForms() {
    document.getElementById("theTable").reset();
}
    /* CSS styles omitted for brevity */
<html>

<head>
    <title></title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel=stylesheet type="text/css" href="temp.css" />
    <script type="text/javascript" src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
        <script type="text/javascript" src="temp1.js"></script>
</head>

<body bgcolor="#FFFFFF" leftmargin="0" topmargin="0" marginwidth="0" marginheight="0">

    <div id="left">
        <form id="theTable"> <b><u>Fruit</u></b>
            /* Form fields omitted for brevity */
        </form>
    </div>
    <div id="right">
        <div id="finResults"></div>
        <center>
            <input id="inputButton" type="button" value="Add" onClick="addOrder()" />
            <input id="inputButton" type="button" value="test" onClick="test()" />
            <input id="inputButton" type="button" value="Show Results" onClick="showOptions(document.getElementById('theTable'))" /> </center>
    </div>
</body>

</html>

Answer №1

To achieve the desired result, simply incorporate a for loop into your test function like this:

function test() {
    console.log(salad);
    for(var i = 0; i < salad.theFruit.length; i++) {
      console.log(salad.theFruit[i] || '');
      console.log(salad.thePrep[i] || '');
      console.log(salad.theOpt[i] || '');
      console.log('');
    }
}

I hope this meets your expectations.

Printing an array typically displays all elements together, separated by commas. This was the behavior in your code, where all fruits were printed at once, followed by preps and opts.

By introducing a loop, we now print elements at specific indexes from all 3 arrays simultaneously. Therefore, the fruit at the first position is displayed, followed by the prep and opt elements at the same index. This pattern continues for elements at subsequent positions in each array.

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

Exploring the Depths of the DOM: Enhancing User Experience with Jquery

I am facing an issue with my AJAX request in my page. After retrieving data from the database and trying to append it to a div, I am attempting to create an accordion interface without success. Below is a snippet of my source code after the AJAX call: ...

Is nesting ajax calls in jQuery a clever strategy?

I currently have this ajax call: $.ajax({ url: "misc/sendPM.php", type: "POST", data: data, success: function(stuff) { if (typeof stuff == "object") { var err = confirm(stuff.error); if (err) { ...

Discovering the specific URL of a PHP file while transmitting an Ajax post request in a Wordpress environment

I'm currently working on a WordPress plugin and running into some issues with the ajax functionality. The main function of my plugin is to display a form, validate user input, and then save that data in a database. Here is the snippet of code for my ...

Res.write inexpressively proceeding without waiting for the completion of an array of promises

snippet const processAll = async (tasks) => { let processes = []; tasks.forEach(task => { if (task === "1") processes.push(asyncProcess1); if (task === "2") processes.push(asyncProcess2); if (task === "3&q ...

JavaScript error: Function is not defined when using Paper.js

UPDATE the problem has been solved by making the colorChange function global I am attempting to modify the color of the path when the 'Red' button is clicked using the colorChange function. Despite my efforts, I keep getting an error stating tha ...

Opening a browser tab discreetly and extracting valuable data from it

Greetings to the experts in Chrome Extension development, I am exploring ways to access information from a webpage without actually opening it in a separate tab. Is there a method to achieve this? Here's the scenario: While browsing Site A, I come a ...

Attempting to alter an image with a click and then revert it back to its original state

I'm currently working on a feature that toggles an image when a specific class is clicked. The code I have so far successfully switches from 'plus.png' to 'minus.png' upon clicking, but I need it to switch back to 'plus.png&ap ...

What is the proper method for utilizing assignments instead of simply assigning values directly?

In the process of developing a markdown editor, I am currently focusing on the functionality of the B (bold) button which needs to toggle. It's important to mention that I am utilizing this library to handle highlighted text in a textarea. Below is t ...

Creating a spherical shape using random particles in three.js

Can anyone assist me in creating a random sphere using particles in three.js? I can create different shapes with particles, but I'm unsure how to generate them randomly. Here's my current code: // point cloud geometry var geometry = new THREE. ...

Issue encountered with create-next-app during server launch

Encountering an error when attempting to boot immediately after using create-next-app. Opted for typescript with eslint, but still facing issues. Attempted without typescript, updated create-next-app, and reinstalled dependencies - unfortunately, the prob ...

Making an Ajax call using slash-separated parameters

Handling APIs that require slash-separated parameters in the URL can be quite tricky. Take for example: http://example.com/api/get_nearest_places/:en_type_id/:longitude/:latitude One way to build this URL is by concatenating strings like so: var longitu ...

Puppeteer failing to detect dialog boxes

I'm attempting to simulate an alert box with Puppeteer for testing purposes: message = ''; await page.goto('http://localhost:8080/', { waitUntil: 'networkidle2' }); await page.$eval('#value&apos ...

Global Variables Evolution as Variables are Assigned

So I'm encountering an issue where running a function and assigning variables to the data seems to be updating my global every time. I've double-checked my code, but I can't seem to pinpoint where the update to the global is coming from. Am ...

Jasmine test failing due to uninitialized angular controller

I encountered some difficulties while writing jasmine tests for an AngularJS application that utilizes angular ui-router. Despite proper initialization of my services and app in the test, I found that the controllers were not starting up correctly. In an e ...

Show the subscription response data in Angular

When utilizing the code snippets below from two different components, I am able to receive a valid response value from the subscriber. dataService.ts fetchFormData(){ return this.http.get('http://localhost:48116/RecuruitmentService.asmx/addRoleTest ...

Contrasting outcomes between calling the await method in a function and directly logging the same method

My code consists of a for loop that iterates through an array. With each iteration, I intend for the loop to extract the value from a specified webpage and then display it in the console. for (let i = 0; i < jsonObjSplit.length; i++) { console ...

Changing the data of a child component that is passed through slots from a parent component in Vue.js

Exploring the world of components is new to me, and I'm currently trying to understand how the parent-child relationship works in components. I have come across component libraries that define parent-child components, such as tables and table rows: &l ...

Unable to load images on website

I'm having trouble showing images on my website using Node.js Express and an HBS file. The image is not appearing on the webpage and I'm seeing an error message that says "GET http://localhost:3000/tempelates/P2.jpg 404 (Not Found)" Here is the ...

Download a JSON file from an angularjs client device

I'm in the process of adding offline functionality to a Cordova app I'm developing. I have a PHP file that retrieves a list of images as JSON, which I then save on the client device using the FILESYSTEM API. However, when I try to display the ima ...

Filtering dynamically generated table rows using Jquery

I'm currently working on a project that involves filtering a dynamic table based on user input in a search bar. The table contains information such as name, surname, phone, and address of users. Using jQuery, I have created a form that dynamically ad ...