Incomplete information is being returned by JavaScript For loop

I am dealing with multiple inputs, specifically textareas with name attributes and some fields being required. Take a look at the example below:

<textarea name="field1" reqired>1</textarea>
<textarea name="field2">2</textarea>
<textarea name="field3" reqired>3</textarea>
<textarea name="field4">4</textarea>

My goal is to extract the name value and check if the field is required. This is how my code looks like:

let customizationInputName=[];
let customizationInputRequired=[];
let customizationInput = document.querySelectorAll('textarea');
for (i = 0; i < customizationInput.length; i++) { 
    customizationInputName[customizationInput[i].name] = customizationInput[i].value;
    customizationInputRequired[customizationInput[i].required] = customizationInput[i].value;
}
console.log(customizationInputName);
console.log(customizationInputRequired);

After running

console.log(customizationInputName)
, I received the correct results for all 4 fields. However, when checking
console.log(customizationInputRequired)
, only the last required field and the last field without required attribute were displayed. Can anyone help me identify the issue in my code?

Answer №1

Simply add customizationInput[i].value and customizationInput[i].required to their respective arrays.

let inputValues=[];
let inputRequirements=[];
let customizationInput = document.querySelectorAll('textarea');
for (i = 0; i < customizationInput.length; i++) { 
  inputValues.push(customizationInput[i].value);
  inputRequirements.push(customizationInput[i].required);
}
console.log(inputValues);
console.log(inputRequirements);
<textarea name="field1" required>1</textarea>
<textarea name="field2">2</textarea>
<textarea name="field3" required>3</textarea>
<textarea name="field4">4</textarea>

Answer №2

Consider consolidating all the necessary information into a single array of objects using ES6:

let inputs = [...document.querySelectorAll('textarea')];
   
let inputArray = inputs.map(textarea =>({name: textarea.name, required: textarea.required, value: textarea.value}))
console.log(inputArray);
<textarea name="filed1" required>1</textarea>
<textarea name="filed2">2</textarea>
<textarea name="filed3" required>3</textarea>
<textarea name="filed4">4</textarea>

Answer №3

Listed below are three issues with the code provided:

  1. The attribute required is misspelled as reqired, which causes it to be false on all elements.
  2. The variables customizationInputName and customizationInputRequired are declared as arrays, but objects are being added to them. The keys 'value' and 'required' need to be set for each object.
  3. In every loop iteration, the required value is being set in customizationInputRequired, even though it can only have true or false values. This results in the object having values from the last two elements, where one has 'required' and the other does not.

By addressing these issues in the modified code snippet below, you should see the desired output in the console:

(function() {
  let customizationInputName = {};
  let customizationInputRequired = {};
  let customizationInputRequiredUnique = {}; //for testing purpose
  let customizationInput = document.querySelectorAll('textarea');

  for (i = 0; i < customizationInput.length; i++) {

    customizationInputName[customizationInput[i].name] = customizationInput[i].value;
    
    if (customizationInput[i].required) {
      customizationInputRequired[customizationInput[i].required] = customizationInput[i].value;
    }
    
    customizationInputRequiredUnique[customizationInput[i].name + customizationInput[i].required] = customizationInput[i].value;

  }
  
  console.log('customizationInputName:', customizationInputName);
  console.log('customizationInputRequired:', customizationInputRequired);
  console.log('customizationInputRequiredUnique:', customizationInputRequiredUnique);
})();
<textarea name="filed1" required>1</textarea>
<textarea name="filed2">2</textarea>
<textarea name="filed3" required="true">3</textarea>
<textarea name="filed4">4</textarea>

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 a new path with Angular

I'm attempting to dynamically change the sp-right class to sp-left in Angular: Html <span class="sp-right"> <label> Number: </label> </span> Directive app.directive("buttonThatTrigger", function () { ...

The browser Internet Explorer fails to recognize the @media screen rule

Currently, I'm focusing on creating a responsive design for a web page. The issue I am encountering involves loading data via ajax to render forms. Strangely, only Internet Explorer seems to think that the width is less than 768px after rendering (thu ...

Automatically reload a particular webpage upon closing a pop-up window (using jQuery)

I am facing an issue with a pop-up named PopUp1 on page0.aspx. The problem occurs when a user clicks on a row in the GridView within PopUp1, causing another pop-up to launch, loading my page1.aspx. The complication arises when the user navigates through l ...

Error: React 404 - Unable to make a POST request with

I am new to utilizing Axios and Node.js as a backend technology. I recently inherited some React code for a login page and I'm struggling to understand why I'm unable to send a POST request to the backend. Below is my .env file: REACT_APP_BACKEN ...

My Next.js app's iframe is being blocked by Chrome. Any suggestions on how to resolve this issue?

I have encountered an issue while trying to display an iframe in my Next.js application. Although the iframe is functioning properly in Firefox, it is being blocked in Chrome. The process of rendering the iframe seems straightforward. Below is the comple ...

Is it possible to show one element while hiding others upon clicking using JavaScript?

Concept My idea is to create a website with a navigation menu where only one section is visible at a time. Each section would become visible upon clicking a specific button in the navigation bar. Challenge I attempted to achieve this using the following ...

Wireframe visualization with rounded corners using Three JS

In my current project involving 3D objects, I decided to experiment with Three.js. My goal is to create a wireframe with rounded corners on a single axis. While I have made progress using two different methods, I'm still facing the challenge of connec ...

The dollar sign is not available during the onload event

Can someone help me with the error I am encountering where $ is unidentified when using onload on my page? This is a simple sample page created to call a function after the page has loaded. Jquery Code $(document).ready(function(){ alert("loaded"); }) ...

Is there a way to showcase time through ApexCharts?

I have been exploring the capabilities of ApexCharts to present data using a timeline chart. The example in Vue just illustrates how to display dates like: new Date(1797, 2, 4).getTime(), new Date(1801, 2, 4).getTime() However, I am curious about how to c ...

How to execute an object function in TypeScript only if it is defined

Currently, I am working on creating a binary search tree class in Typescript as part of my learning journey with the language. My aim is to incorporate generics into this exercise. In the process of implementing algorithms within the class, I have encount ...

Exploring the power of Mongoose.js and using the query object with Regular Expressions

In an application focused on locomotives, the search functionality queries models with specific metadata. To check against the keywords field, I need to include a regexp engine. My current approach is as follows: this.keywords = strings.makeSafe(this.par ...

When the jGrowl function is triggered, it disrupts the functionality of the thickbox in conjunction with UpdatePanel

Whenever a link is clicked, I trigger a thickbox like this: <a href="createContact.aspx?placeValuesBeforeTB_=savedValues&TB_iframe=true&height=400&width=550&modal=true" title="Add a new Contact" class="thickb ...

Challenge: RxJS timeout function not functioning as expected

I am facing an issue with exiting the Observable stream after 3 seconds if there is no new string input. The problem arises when I paste the same value multiple times, as the distinctUntilChanged operator prevents the input stream from progressing. I wan ...

Utilizing JS Underscore for combining and organizing arrays with common keys

I am facing a scenario where I have two arrays: "array_one": [ { "id": 1, "name": One }, { "id": 2, "name": Two } ] "array_two": [ { "id": 1, "name": Uno }, { "id": 3, "name": Three ...

What is the best way to bind a click handler or any event handler to my object or module?

Can someone help me with attaching event handlers to my module in a way that I am not sure how to achieve? Here is the snippet of my module: var globalModule = { name:'Banana on princess bed', init:function(){ alert('Init ...

ngModel is not taken into account when processing form data

Attempting to make use of a dynamic form in AngularJS, the code snippet below has been utilized: <dynamic-form template="formTemplate" ng-model="formData" ng-submit="processForm()"> </dynamic-form> The controller script inc ...

How can a Spinner be incorporated into a Button within a Modal while running in the background?

I'm attempting a rather simple task, but I'm encountering difficulties. The issue I'm facing involves a modal that prompts the user for confirmation. Once the user clicks "confirm," a URL is fetched, triggering a background process. During ...

Vue/Vite vanilla setup encountering a 'Failed to fetch dynamically imported module' TypeError

We're currently working with a vanilla Vue/Vite setup and I'm encountering the error message TypeError: Failed to fetch dynamically imported module in Sentry logs. It appears that these errors coincide with new deployments to production, but I d ...

Tips for displaying the response next to the corresponding table data (td) cell

When I click the fourth button, the response is showing on the first td. I want to show the response next to the respective td. Below is my code, can someone help me? Thanks. (i.e., here I am getting the $status using a query, but I want this status to di ...

Angular is attempting to call the $http method and trigger the success callback even

I have implemented a function in a service: function retrieveData(link) { return $http.get(link).then(function (res) { return res.info; }); } If the request is successful, everything works smoothly - I receive a promise as expected. Howe ...