An issue with repetitive looping in eventHandler in Javascript

Within an HTML page, I've implemented Javascript code that displays elements on a form when a user clicks the + button and removes elements when the - button is pressed. However, I encountered an error "TypeError: docs[n] is undefined" after following this sequence of events:

  1. Click on the button to add elements
  2. Remove unnecessary elements
  3. Add back the removed elements (Error occurs)

I would greatly appreciate any assistance in resolving this issue.

`<script language="JavaScript">`
        
       var idx = 0;


        var d;

            //Ensuring getElementsByClassName functions across all IE versions
            if (!document.getElementsByClassName) {
                document.getElementsByClassName = function (cn) { 
                var rx = new RegExp("(?:^|\\s)" + cn+ "(?:$|\\s)");
                var allT = document.getElementsByTagName("*"), allCN = [],ac="", i = 0, a;
                while (a = allT[i=i+1]) {
                  ac=a.className;
                  if ( ac && ac.indexOf(cn) !==-1) {
                    if(ac===cn){ allCN[allCN.length] = a; continue;   }
                    rx.test(ac) ? (allCN[allCN.length] = a) : 0;
                  }
                }
            return allCN;
        }
    }
            function add_fields(e) {

            //Saving existing values before adding new fields
            var docs = document.getElementsByClassName("doc");
            var revs = document.getElementsByClassName("rev");

             ++idx;

            /*  console.log("test " + idx); */

            var saveDocs = new Array(idx); 
            var saveRevs = new Array(idx);

            for (n=0; n < idx; n++) {
            saveDocs[n] = docs[n].value;   **//Error occurs here**
            saveRevs[n] = revs[n].value;
            }


            node = document.getElementById("content");
            theNewRow = document.createElement("tr");

                theNewCell = theNewRow.insertCell(0);
                theNewCell.innerHTML = "Approver Name";
                theNewCell.setAttribute("style","font-size: 12pt");

                theNewCell1 = theNewRow.insertCell(1);
                theNewCell1.innerHTML = "<input type='text' class='doc' style='width:180px;' id='docNum0'/>";
                theNewCell1.setAttribute("style","padding-left: 10px");

                theNewCell2 = theNewRow.insertCell(2);
                theNewCell2.innerHTML = "Approver Email";
                theNewCell2.setAttribute("style","font-size: 12pt");
                theNewCell2.setAttribute("style","padding-left: 10px");

                theNewCell3 = theNewRow.insertCell(3);
                theNewCell3.innerHTML = "<input type='text' class='rev' style='width:180px;' id='rev0'/>  <input class='minusThing' type='button' style='font-size:10px' value='- '/>";
                theNewCell3.setAttribute("style","padding-left: 0px"); 



                node.appendChild( theNewRow );



            // Restoring old arrays and assigning IDs to the newly added fields
            docs = document.getElementsByClassName("doc");
            revs = document.getElementsByClassName("rev");
            for (n=0; n < idx; n++) {
            docs[n].value = saveDocs[n];
            revs[n].value = saveRevs[n];
            } 


            docs[idx].id = "docNum" + idx;
            revs[idx].id = "rev" + idx; 
                }


            // Looping through the entries
            function myfunction() { 

                alert('Inside Function')

               var values = ""; 
               for (n=0; n <= idx; n++)
               {               
                var doc = document.getElementById("docNum"+n).value;
                var rev = document.getElementById("rev"+n).value;


                //alert(doc+rev);


                 //Call VbScript Sub and pass value
                    PassValues(doc,rev);
     

Answer №1

When you have deleted all the documents, using

document.getElementsByClassName("doc");
will result in an empty array being returned. Additionally, if you increase the value of idx before entering your loop, the loop will only run once and attempt to access docs[0], which is not defined.

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

The endless $digest loop issue arises when attempting to filter an array of objects

Encountered a persistent $digest loop issue while passing parameters to a custom filter defined on the $scope. Here's the snippet in HTML: <ul id="albumListUL" class="fa-ul"> <li ng-repeat="album in GoogleList | myFilter:Field:Reverse t ...

The defined function in Node.js did not work properly with the callback

This code snippet demonstrates how to use the findOne() method with Node.js and MongoDB. var MongoClient = require('mongodb').MongoClient; MongoClient.connect('mongodb://localhost:27017/blog', function(err, db) { if(err) throw er ...

Guide to utilizing jQuery for setting values in all subsequent rows of a table

I have a table with 15 rows of text boxes labeled as text1, text2, and so on up to text15. If I enter text into, let's say, the 5th textbox, I want that same text to be automatically copied into all subsequent textboxes from the 6th through the 15th. ...

Getting the alt value and text of an <img> tag and placing it into a textarea

I have a textarea that contains the following content: <textarea id="testContent"> <img src="..." alt="value"> My text.... </textarea> I am aware that I can use javascript to specifically target and retrieve the alt value of the img ele ...

Is it possible to capture and generate an AxiosPromise inside a function?

I am looking to make a change in a function that currently returns an AxiosPromise. Here is the existing code: example(){ return api.get(url); } The api.get call returns an object of type AxiosPromise<any>. I would like to modify this function so ...

What is the best way to retrieve information from a web service using Vue.js within an HTML environment?

I'm trying to retrieve data from a web service using vue.js, but I'm having trouble fetching the data. Can I use vue.js without installing node.js? Any help would be appreciated. Thank you in advance. <!DOCTYPE html> <html lang="en> ...

Generate sequential keys for objects in an array

Looking for assistance; Imagine I have an array of objects structured like so { 'Name:'ABC', 'Code': 'BP' } What is the most effective method to add an incremental attribute to this array in typescript. [{&apo ...

Icon displayed within the input field

Is there a simple method to add an input text element with a clear icon on the right side, similar to the layout of the Google search box? I've searched, but I could only find instructions for placing an icon as the background of the input element. I ...

Retrieve a specific quantity of items from an array

I recently started using Postman to develop some test cases. Many of the responses I receive with the get method contain large arrays with numerous objects (I have simplified them here for readability, but each object actually has over 20 properties). Cu ...

Node server quickly sends a response to an asynchronous client request

Apologies for my lack of writing skills when I first wake up, let me make some revisions. I am utilizing expressjs with passportjs (local strategy) to handle my server and connect-busboy for file uploads. I believe passport will not have a role in this pr ...

Encountered a Socket.io issue: CONNECTION_TIMED_OUT_ERROR

I'm in the process of developing a simple HTML chat program. I've set up a node server for testing, but encountering a socket error when trying to access the HTML page. This is my first experience with Node.js and setting up a server, so it' ...

The React functional component captures a snapshot of its state when initializing a websocket event handler

When using a react functional component, it captures a snapshot of the state at the time of subscription. For example, refer to the code below. If I click the setSocketHandler button and then press the setWelcomeString button. If I receive a message over ...

Creating Responsive Image Map Areas in HTML

Implementing image maps on my website has been a challenge because of the lack of responsiveness. I am struggling to adjust the size of map areas when resizing the window. If anyone can help with this issue, I am open to using either JavaScript or CSS met ...

Using jQuery to update a specific item in a list

My current project involves developing an Image Gallery app. It uses <img> tags within li elements. The code snippet is as follows: var $slideR_wrap = $(".slideRoller_wrapper"); var $slidesRoller = $slideR_wrap.find(".slidesRoller"); var $slideR ...

What is the best way to monitor parameter changes in a nested route?

I need assistance with managing routes const routes: Routes = [ { path: 'home', component: HomeComponent }, { path: 'explore', component: ExploreComponent, children: [ { path: '', component: ProductListC ...

The express-fileupload throws an error saying "ENOENT: unable to locate the file or directory at 'public/images/name.ext'"

I am encountering an error ENOENT: no such file or directory, open 'public/images/name.ext from express-fileupload. I have searched for solutions to this issue, but none of the ones I found seem to work for me. Here are two examples: No such file or d ...

What is the best way to include an Observable in this function?

Every time I send a set of credentials to my API and receive the data that needs to be stored, I encounter an error during the login process. Error: TypeError: You have provided an invalid object when a stream was expected. You can provide an Observable ...

A guide to querying JSON data in a backend database with JavaScript

My backend JSON DB is hosted on http://localhost:3000/user and contains the following data: db.json { "user": [ { "id": 1, "name": "Stephen", "profile": "[Unsplash URL Placehol ...

What is the way to retrieve an array property in a typescript interface?

Imagine a scenario with three interfaces structured as follows: registration-pivot.ts export interface RegistrationPivot { THead: RegistrationPivotRow; TBody: RegistrationPivotRow[]; } registration-pivot-row.ts export interface RegistrationPivotR ...

Utilizing Typescript in conjunction with a personalized React hook

Exploring how to create a unique custom react hook in TypeScript that can take an object with all optional React.CSSProperties as keys, such as... const example = useExample({ font: { initial: 'Arial', new: 'Roboto' } }) ...