Obtain the value of a JavaScript form with a dynamically generated field name

I am struggling with a simple javascript code and for some reason, it's not working.

var number = 5;
var netiteration = "net"+number;  // now netiteration is equal to net5

var formvalue = document.forms.myformname.netiteration.value;

Why is this code unable to retrieve the value from the form field named "net5" in the form with the name/id of "myformname"?

Also, I am using a JavaScript book that is 10 years old, could it be possible that the syntax has changed since then?

Thank you

Answer â„–1

Consider the following:

let count = 8;
let totalcount = "total"+count;  // assigns totalcount as total8

let value = document.forms.formname[totalcount].value;

Your initial code was searching for a field named "totalcount", but you actually need the field with a name matching the calculated value of totalcount.

Answer â„–2

Unfortunately, using a variable like netiteration within the HTML DOM structure will not function properly.

A potential solution could look something like this:

var formElements = document.forms.myFormName.getAllChildren();
var netElements = new Array[10];
for(var j=0;j<formElements.length;j++)
{
   var name = formElements[j].name;
   if(name.indexOf('net') != -1)
    netElements[j] = formElements[j];
}

Now, the array netElements contains all elements with the name 'net' in it...

I hope this helps address your issue!

Answer â„–3

Stumbled upon this gem and decided to spice it up with some additional insights for those who may find it valuable.

If you happen to be using id attributes in your form fields, you can also reference them like so:

<input type='text' id='myfield1' onclick="Example(1)">
<input type='text' id='myfield2' onclick="Example(2)">

Then in your JavaScript code, you can access the field using a variable like this:

function Example(myvar){
    var myvalue=document.getElementById('myfield'+myvar);   
    console.log('The value is '+myvalue);
}

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

Resolved plugin issue through CSS adjustments

Take a look at this template 1) After referring to the above template, I developed a fixed plugin using JavaScript. 2) Clicking the icon will trigger the opening of a card. 3) Within the card, I designed a form using mdb bootstrap. Everything seems to ...

Reliable Dropdown Navigation Bars

Once I have successfully implemented three dynamic drop down menus using the combination of jQuery, AJAX, and PHP, the next challenge arises. After populating the dropdown menus based on user selections (e.g., selecting a value in the first dropdown menu ...

Are there any user interface frameworks available that can replicate the aesthetic of a Mac application?

I've been searching high and low but I haven't come across any answers yet. It caught my attention that the wunderlist mac app was developed using HTML/CSS/JS, but I'm curious if they incorporated a pre-existing UI JavaScript framework into ...

When trying to deploy to Heroku, node-gyp encounters an issue installing [email protected] and ultimately fails to rebuild

I am currently facing an issue with deploying a nodejs application on Heroku due to the node-gyp rebuild error associated with the base64 library. I have successfully run the application locally, but deployment on Heroku seems to be problematic. Any sugges ...

Error: The call stack has reached its maximum size while running an npm install

Attempting to execute npm install, encountered the following console output: npm ERR! Linux 4.8.0-27-generic npm ERR! argv "/usr/bin/nodejs" "/usr/bin/npm" "install" npm ERR! node v6.9.1 npm ERR! npm v3.10.8 npm ERR! Maximum call stack size exceeded npm ...

Executing a NodeJS function from a JavaScript function

I am working on a project involving Firebase and I am looking to connect a server-side function that can send an email to the client-side script. Below is my server-side index.js file: const functions = require('firebase-functions'); var nodema ...

Adding a Stripe pay button using Jquery append results in the return of an [object HTMLScriptElement

I'm currently working on dynamically adding the Stripe pay with card button through jQuery. I've decided to append it because I only want it to show up once a specific condition is met by the user, as well as due to the fact that the pricing can ...

Accessing instance variables from a chained observable function in Angular 2/Typescript

Currently, I am utilizing Angular2 along with Typescript. Let's assume that there is a dummy login component and an authentication service responsible for token authentication. In one of the map functions, I intend to set the variable authenticated as ...

Looking for assistance with updating a JavaScript Object Array and embedding it into a function

Below is the code snippet I am working with: $("#map4").gMap({ markers: [ { address: "Tettnang, Germany", html: "The place I live" }, { address: "Langenargen, German ...

When I try to access localhost, it directs me to http://localhost:3000/myprofile%20 instead of localhost:/3000/myprofile

Every time I try to log into my profile page with the correct login credentials, I get redirected to http://localhost:3000/myprofile%20, but then receive a 404 error. This is what my code looks like: // Login Route router.post('/login', functi ...

An unexpected identifier error occurred following an Ajax request

Below is the HTML code that I am working with: <div id="texttheory" class="centertext">'. $short .' </div>'; <button id="thbutton" class="theory_button" onclick="javascript:changetheory('.$long.')"> <im ...

Can you explain the concept of cross domain and how JSONP fits into the picture?

As a beginner in .net programming, I have created a webservice where JavaScript calls the webservice in my code. I attempted to call it using my phone's browser while on the same network. It works perfectly with localhost, but when trying to call the ...

Different ways to maintain the original syntax highlighting colors in JavaScript console

Upon closer inspection near the green arrows, you can see that the default console.log function colorizes values based on their type, distinguishing between string and number. In contrast, highlighted near the red arrows is my attempt at using Winston to ...

How to retrieve document.getElementsByName from a separate webpage using PHP and javascript

Hey there, I've been searching for a solution to this issue but haven't had any luck so far. I'm attempting to retrieve the value of the name test from an external website. <input type="hidden" name="test" value="ThisIsAValue" /> Up ...

Implementing styling upon app mounting in Vue.js - a step-by-step guide

Hey, I'm working with a template code that looks like this: Here's my script code: data () { return { loadPage: true } }, mounted () { this.loadPage = true }, And here is my styling code: #app{ width: 100%; opacit ...

Navigating through ajax requests on a Leaflet map

Currently, I have a leaflet map set up with the leaflet-panel-layers plugin to create a visually appealing layer control. To create my layers and overlays, I have two functions in place. The issue arises when trying to access external geoJSON files, as lea ...

How can I find the last element that was selected using XPath in the browser console

Need help with XPath: $x(("//div[@class='ag-header-row']))[1] I'm working with an array of divs, but I want to select the last one. The [1] is necessary due to multiple rows with this class. I’ve heard about using [last()], but unsure w ...

Users are encountering timeout issues when attempting to connect to the Azure Postgres flexible database through the node.js server deployed on the Azure App Service

My node.js express server is deployed on Azure App Services, connecting to an Azure flexible Postgresql database. Strangely, everything works fine when running the server locally, but once it's deployed to Azure App Service, all requests time out: Th ...

The local ESlint plugin is causing issues with installing dependencies on our CI environment

I have developed a personalized ESLint plugin specifically for one project and have not made it public. It is saved in a folder within my project because I only intend to use it internally, and I see no need to create a separate repository for it. However, ...

Tips for extracting JSON data from an API with identical names as values

I am working on a project to create a data search system using JSON. The JSON data is stored in a REST API, and the structure of the API is as follows: [ { "info": "cute but big animal", "type": "pig", ...