Save the processed string into a new array

Will my experimental code function and behave in the same way as my working code, given that the HTML, CSS, and previous JS are functioning properly?

If not, what is causing the discrepancy? Additionally, how can I go about creating a loop-array style version of my code?

Experimental code:

var currentAccount = [];
var fieldList = ["firstName","lastName","age","gender"];

for (var i = 0; i < fieldList.length; i++) {
    JSON.parse(fieldList[i]) = document.getElementById(fieldList[i]).value;
    currentAccount.push(JSON.parse(fieldList[i]));
}

Working code:

var currentAccount = [];
var firstName, lastName, age, gender;

firstName = document.getElementById("firstName").value;
lastName = document.getElementById("lastName").value;
age = document.getElementById("age").value;
gender = document.getElementById("gender").value;

currentAccount = [firstName, lastName, age, gender];

Answer №1

How can I transform my code into a loop-array style version?

Here's an example:

const fieldIds = [ "username", "email", "password", "phone" ];
const userData = fieldIds.map( (id) => {
  return document.getElementById(id).value;
})

Answer №2

Avoid the use of JSON.parse() in your test code:

for (let i = 0; i < fieldList.length; i++) {
    let fieldValue = document.getElementById(fieldList[i]).value;
    accountArray.push(fieldValue);
}

Answer №3

Check out this innovative approach utilizing ES6 along with a different method of utilizing document.getElementById. See how it works!

const getElement = function( id ) { return document.getElementById( id ); };
const formFields = [ "username", "password", "email", "phone" ];
const userDetails = formFields.map((field) => {
    return getElement(field).value;
});

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

Establish a JavaScript hyperlink to assign a value to a shared rendering parameter

In my attempt to create a JavaScript link that, when clicked, assigns a value to a public render parameter in WebSphere Portal, I'm encountering unexpected code instead of the intended value. Here is how I am constructing the link using JavaScript: ...

Unable to pass an event parameter using my this.handleChange function in react-native

Encountering an issue with the error message "undefined is not an object (evaluating 'event.preventDefault)" It appears that I am unable to pass an event parameter to the handleChange function in my child component, which is being rendered in the par ...

The functionality of .on is disrupted by a dynamically generated table through ajax

I am currently using ajax to dynamically generate a table. Once a user inputs a query, a new table containing data is created and replaces the existing content within #content-display: function searchQuery(query){ $.ajax({ url: "search.php", ...

Having trouble creating a report with an HTML screenshot using Protractor

Need assistance with generating reports using a html screenshot in Protractor. I have followed all the necessary steps but encountered an error. Any help would be appreciated. Here is my conf.js: // Sample configuration file. var HtmlReporter = require(& ...

Exploring the power of Angular 2 Directive scopes

When it comes to Angular2, Directives do not come with "scopes", unlike Components. However, in my specific case, I require a Directive to establish a scope. Take a look at my App component - it contains an HTML template, and the foo directive could potent ...

Using Angular Material for creating tabs with identical content

I am using material with angularjs and have encountered an issue with my two md-tabs. Both tabs have a similar DOM structure, but contain some unique content. Instead of duplicating the common DOM twice, I am looking for an alternative solution. Is it poss ...

Having difficulty interpreting JSON Object, converting to a string, or accessing JavaScript property

My current challenge involves utilizing a Firefox addon that supplies me with the following variable: [{errorMessage:"TypeError: a is null", sourceName:"http://pagead2.googlesyndication.com/pagead/js/graphics.js", lineNumber:17, console:null}] From Fire ...

Verify the REST call for access to Google APIs

Having issues with authenticating a REST request for Google APIs. Typically, Google provides client packages to handle this process. Currently using the Document Translation service which is still in preview, so unable to use the package. The documentatio ...

Multi selection dropdown feature in Angular failing to populate the options

I am working on a small Angular controller that manages a dropdown menu, with the second dropdown menu populating based on the selection made in the first one. Despite my best efforts, I can't seem to populate the dropdown menus with any content from ...

Error in Node: JSON parse failure due to invalid token "'<'" and ""<!DOCTYPE ""

Every time I attempt to run node commands or create a new Angular project, I encounter the following error. Node version 20.11.0 NPM version 10.2.4 https://i.sstatic.net/Dg6BU.png https://i.sstatic.net/ZwN1Q.png ...

Executing Scripts inside an iFrame in Angular

Upon receiving an API response, I am presented with HTML as a string. Inside this HTML are internal script tags that contain functions called under $(window).load(). How can I successfully load this HTML within my Angular app? I attempted to append the HT ...

Building a table in Quasar by utilizing nested objects

I am currently facing an issue while using Quasar to create Q-Tables. I am struggling with incorporating nested objects with dynamic key names. Below is the content of my table: data: [ { 'FrozenYogurt' : { &a ...

Ways to combine multiple dictionaries in Python with more than 2 dictionaries

As a student new to Python, I attempted to create code that calculates total marks and percentages by adding 9 dictionaries together. Despite trying various methods like +, combine_dict, merge_dict, in search for answers for the past few days, I have not f ...

Increasing the Length of a String by 1-5 Characters

I am trying to manipulate a Java String to become a multiple of 5 by adding X's to the end: For example: "ABCDEFGHIJK" // length 11 Adding 4 "X" to the end should result in: "ABCDEFGHIJKXXXX" // length 15 Another example: "ABCDEFGHI" // length 9 ...

GET request being blocked by iframe

I recently encountered a problem with my hosted payment page that is loaded within an iframe. After the transaction is complete, the payment provider attempts to use a URL specified by us in the iframe to navigate away from it and perform any necessary ac ...

What is the best way to transform an array of objects into a single string in JavaScript?

After receiving the input from req.body, it looks like this: [ { "Name": "Test_1", "Level 1": "Story_1", "Level 2": "Story_1.1" }, { "Name": & ...

Issue with setInterval function execution within an Angular for loop

My goal is to dynamically invoke an API at specific intervals. However, when attempting to utilize the following code snippet in Angular 7, I encountered issues with the interval timing. I am seeking a solution for achieving dynamic short polling. ngOnIn ...

Workbox background sync - Retrieving replayed API responses

Currently, I am utilizing the Workbox GenerateSW plugin and implementing the backgroundSync option within runtimeCaching. You can find more information in the documentation here. This powerful plugin enables me to monitor APIs and successfully retry faile ...

Observing the occurrences of JavaScript events

Is there a way to track all JavaScript events in the browser? Such as, identifying the functions that have been executed and the parameters that have been passed in each JS file? I'm dealing with some obfuscated code and I'm looking to determine ...

Bootstrap alert JS refuses to slide down

Here is the JavaScript code to make a blue bar slide down on click: $('#comment').click(function(e) { e.preventDefault(); $('#comment').slideDown(); }); ...