Retrieve data from input fields using an array

I am currently developing a form that allows users to add multiple inputs like so:

<script type="text/javascript">
   <!--

   var counter = 0;
   var limit = 4;
   window.onload = moreFields;
   function moreFields() {
    if (counter == limit) {
              alert('You have reached the limit of adding ' + counter + ' inputs');
         }
         else

    var newFields = document.getElementById('sa-groep').cloneNode(true);
        newFields.id = '';
        newFields.style.display = 'block';

    var newField = newFields.childNodes;
    for (var i = 0; i < newField.length; i++) {
        var hetId = newField[i].id
        if (hetId)
            newField[i].id = hetId + counter;
    }

    var insertHere = document.getElementById('writeroot');
    insertHere.parentNode.insertBefore(newFields,insertHere);

    counter++;
    }

Everything is working as intended, each input field is getting a unique id. However, I realized that it would be more efficient to fetch all the input values using getElementsByClassName. So I created a function to achieve this:

function getClassValue() {

    var secAut = [];
    var readyItems = document.getElementsByClassName('SA');
        for(var i = 0; i < readyItems.length; i++){
        secAut.push(readyItems[i].value);
        document.write(3011+i+  " contains: " + secAut[i] + "<br />");
        }
        }

Here is the corresponding HTML code:

<body>

<div id="sa-groep" style="display: none">
    <input class="SA" id="sa_" value=" " /> 

    <select class="RC" id="rc_"> 
        <option>Rating</option>
        <option value="excellent">Excellent</option>
        <option value="good">Good</option>
        <option value="ok">OK</option>
    </select><br /><br />

    <input type="button" value="Remove review"
        onclick="this.parentNode.parentNode.removeChild(this.parentNode)" /><br /><br />

</div>

    <span id="writeroot"></span>

    <input type="button" onclick="moreFields()" value="Give me more fields!" />

    <input type="button" onclick="getClassValue()" value="Send form" />

</body>

However, when I try to execute the function, it only displays: 3011 contains: So, what am I missing here?

Answer №1

Upon initial inspection, my recommendation is for you to refrain from using document.write (as it replaces all text on your document) and instead utilize console.log("something..") or the innerHTML property within a designated div.

As previously mentioned, document.write will overwrite all content on the page with the string provided.

Answer №2

An issue next to the curly brace (shoutout to @James) was caused by cloning hidden fields, resulting in an empty element at the beginning of the arrays. To remove the first element of an array, I used the shift() method. Although there might be room for improvement, this is my current solution:

function getClassValue() {

var secAut = [];    // array containing names of secondary authors
var readyItems = document.getElementsByClassName('auteur');
    for(var i = 0; i < readyItems.length; i++){
    secAut.push(readyItems[i].value);
    }
var secAutMinus = secAut.shift(); // remove 1 element from array because the first input is empty (display: none)

var relCode = [];   // 2nd array containing relationship codes
var relCodeready = document.getElementsByClassName('relcode');
for(var i = 0; i < relCodeready.length; i++){
    relCode.push(relCodeready[i].value);
    }
var relCodeMinus = relCode.shift(); // remove 1st element

    for(var k= 0; k < secAut.length; k++){
    console.log(3012+k+  ' contains: ' + secAut[k] + ' is ' + relCode[k] + '<br/>'); // reading arrays excluding the first empty element
    }
    }

Answer №3

To ensure the loop functions properly, it is necessary for it to begin at 1 because the 0th element is actually the hidden (cloned) one.

function fetchClassValues() {

  var secAut = [];
  var readyItems = document.getElementsByClassName('SA');

  for (var i = 1; i < readyItems.length; i++) {
    secAut.push(readyItems[i].value);
    document.write(3011 + i + " contains: " + secAut[i - 1] + "<br />");
  }
}

Furthermore, there are a few other issues such as a missing curly brace after the else statement in moreFields.

Check out this functional fiddle

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

How can the issue of the background fill option covering multiple loading bars be resolved?

I am currently relying on Google Translator, so there may be errors in the translation. The issue I am facing is that when I add a parameter with the "fillColor: '#f4f5f9'", the wheel covers one of the elements of Multiple Bars. I have modified ...

Exploring the function of variables in VueJS

I'm facing a tricky issue with VueJS as I am still getting acquainted with it. My objective is to access and modify variables within the data function, but so far, I haven't been successful. The problematic line: console.log('item: ' ...

What is the best way to execute a callback once a mongoose findOneAndUpdate operation has successfully completed

Within my API, I utilize the app.put method in Express to search for a document in a collection with a specific title using Mongoose's findOneAndUpdate method for updating. app.put("/articles/:articleTitle",(req, res) => { Article.fin ...

Using jquery to toggle active nav links in Bootstrap

I'm currently working on integrating a jQuery function to automatically update the active status of the navigation links in my Bootstrap Navbar. The structure involves a base HTML file that extends into an app-specific base file, which is further exte ...

Changing the text color and background color of a span element when a ng-click event is triggered

There are two buttons, Today and Tomorrow, each with an ng-click function. By default, the button background color is white and text color is red. When the Today button is clicked, the background color changes to blue and the text color changes to white. ...

Angular ngView not displaying content on the page

To load a ngView page by clicking on a link, the html file does not appear as expected. Running the application directly without using localhost might be causing the issue. I simply opened index.html with Chrome browser, so it's possible that there i ...

Have I potentially compromised my project by executing the command `npm audit fix --force`?

While working on a React project using Vite, everything was going smoothly. I decided to incorporate some charts and came across the recharts package, which I found quite appealing. So, I added it to my project using the command npm i recharts. After runn ...

Getting the toState parameter using the $transitions service in the latest version of the ui-router

In my project, I am currently utilizing ui-router version 1.0.0-alpha.3. Please note that the older events have been deprecated in this version. As a result, I am in the process of migrating from: $rootScope.$on('$stateChangeStart', (event, toS ...

Issue encountered with websocket connection while attempting to include dependencies

My current project involves integrating charts for the graphical component using React within an Electron software. I've added interaction with buttons (sections) to insert different data into the graphs based on user clicks on one of the sections. Th ...

Improving efficiency for handling a vast number of inputs in React applications

Dealing specifically with Material UI, I am faced with the challenge of rendering a large number of inputs (more than 100) while effectively managing global state. Performance issues arise when using the Material UI <TextField /> component, with noti ...

Toggling in JS does not alter the DIV element

I attempted to utilize Bootstrap toggle to modify the div HTML content similar to the example shown at with a slight modification, but unfortunately, it did not function as expected due to a discrepancy in my current JavaScript code. I am unsure of what I ...

Can a double array be classified as an object?

Yesterday, we took a test and one of the multiple choice questions was: If you have the following variables declared in your code, how many objects would you have? double[] number = new double[6]; int number2 = 0; I selected 2 as my answer since there ...

React/Javascript - Executing Function returns prematurely

I have been working on a function that takes an object and iterates through it to create a search query. However, the issue I'm facing is that the function returns before I finish looping through the object: export default function buildQuery(query) ...

How to send route parameters to a controller function in ExpressJS

I'm currently working on setting up user authentication for my application using passport JS. I am facing a challenge in passing the passport variable between app.js, routes.js, and controller.js. Despite trying various approaches, I have been unsucce ...

Unable to establish a connection with the default port on Mongo DB while utilizing Node.js

I am new to using Node.js and I'm trying to establish a connection with MongoDB in my Node.js application, but I'm encountering issues. Here is the code snippet: var mongo = require("mongodb"); var host="127.0.0.1"; var port=mongo.Connection.DE ...

send back information obtained via an ajax request made by a javascript module

Here is a code snippet featuring an object with a function that makes an AJAX call. The function currently returns an empty array, but we need to figure out how to return the data after receiving the response. var receivedData = []; var AjaxUtil = { ...

Transmitting Several Pictures at Once Through WhatsApp-WebJS

I have encountered a challenge while attempting to send multiple images in a single WhatsApp message using the WhatsApp-WebJS library. Despite receiving a "success" confirmation without any errors, the images and message fail to appear on WhatsAp ...

Incorporating middleware to handle 404 errors in Express

scenario app.use("/api/tobaccos", tobaccos); app.use(function(err, req, res, next) { console.error(err.message); }); API details: router.get("/:id", async (req, res) => { console.log("GET TOBACCO:" + req.params.id); ...

AngularJS $scope variable issue

After searching online, I found this code snippet that I tried to implement, but unfortunately, it's not displaying any data. Below is the HTML code: <html data-ng-app=""> <head> <title>Example 4: Using AngularJS Directives an ...

In NextJS 12, an UnhandledPromiseRejectionWarning occurs when trying to reference the TextEncoder which is not defined

Currently, I am working on developing a Spotify clone using NextJS 12 along with a Tailwind CSS template. To initiate the project, I executed the following command: npx create-next-app -e with-tailwindcss spotify-2. The project was successfully created, b ...