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

Is the JavaScript Date object consistently displayed in the America/New_York timezone?

The server sends me a time-stamp in milliseconds (Unix time / time from Epoch) with the constant timezone "America/New_York". On my client side, I want to ensure that the time is displayed according to the America/New_York timezone. I have been using Joda- ...

Checking if the iframe location has been modified using Jquery

Looking to determine if the location of an iframe has been modified. function checkLocation() { setInterval(function(){alert("Hello")},3000); if (document.getElementById("myiframe").src = 'http://www.constant-creative.com/login';) { } ...

Retrieving data from the firebase database by filtering based on the child's specific value

Looking at the firebase database, I can see that only the 'name' field is available. Now, I am trying to retrieve the 'quantity' value associated with that specific 'name'. Can someone provide me with a sample firebase query i ...

Autonomous JQuery Modules

Is it possible to separate the functions in JQuery and use only the ones needed by splitting the file with PHP? By doing this, I aim to improve page speed, save bandwidth, and have more control over the functions used through the backend. Can the functio ...

Converting a JS result set into JSON format

Having an issue with converting code from XML output to a JSON object instead. Here is the current code: public String evaluate() throws Exception { // Code block here } I need assistance in using GSON JSON utility methods to convert the result s ...

"X-Requested-With" header not being included in XMLHttpRequest request

After successfully using jQuery.ajax() to make an ajax call to an MVC action, I decided to switch to using the XMLHttpRequest along with the HTML5 File API due to some forms containing file controls. However, since making this change, the MVC action no lon ...

Tips on sending multiple values to AngularJS Directive

Currently, I am in the process of creating a simple AngularJS directive. As I am still very new to AngularJS, I would appreciate it if the answers provided could be simplified! The directive I am working on is essentially a combobox. For those unfamiliar ...

When HTML elements are dynamically inserted through JavaScript using quilljs, they may cause conflicts with the layout properties

I am currently working on creating a simple webpage layout similar to that of Stack Overflow, with a sidebar and a main content area that can scroll. In my case, the content area is intended to host a QuillJS text editor. To integrate the QuillJS editor i ...

Organizing a Vue.js SPA project: Implementing Vuex store and API calls efficiently

Here is how I have organized the structure of my Vue app: components/ article/ AppList.vue common/ AppObserver.vue NoSSR.vue layout/ AppFooter.vue AppHeader.vue ui/ AppButton. ...

Perform the action: insert a new item into an array belonging to a model

Here is the structure of my model: var userSchema = new mongoose.Schema( { userName: {type: String, required: true}, firstName: {type: String}, lastName: {type: String}, password: {type: String, required: true}, ...

Tips for creating incremental progress on a pop-up page?

I am looking for guidance on creating a page with specific functionalities. Here is what I have in mind: I want to implement a button that opens a popup when clicked. The popup should display static instructions and buttons for the user to progress throu ...

Adjust the value based on selection

I aim to display another div when either the Full Time or Part Time option is selected. Additionally, I would like to calculate a different value for each option; if 'Part Time' is chosen, PrcA should change to PrcB. Here is the code snippet tha ...

encountering the issue of not being able to assign a parameter of type 'string | undefined' to a parameter of type

Seeking help with the following issue: "Argument of type 'string | undefined' is not assignable to parameter of type" I am unsure how to resolve this error. Here is the section of code where it occurs: export interface IDropDown { l ...

The @Mui datepicker seems to be causing some trouble with the react-hooks-form integration

Below is a code snippet where I showcase working and non-working sections (commented out). <Controller control={control} name="DOB" render={({ field }) => ( <LocalizationProvider dateAdapter={AdapterDayjs}> <DatePic ...

The identical items combined into a single array

I have a specific data structure that I am struggling to manipulate in JavaScript. The goal is to merge objects with the same invoice_nr into one array, while keeping other objects in separate arrays. const result = [ { invoice_nr: 16, order_id: ...

Sleek descending motion effect

I have created a simple function, but it is not animating smoothly and seems to lag... I am using it for a div sized at 1600x700 pixels on page load $(document).ready(function(){ $('#slider').slideDown(500); }); Is there any way to ensure s ...

What are some ways to maintain code efficiency when working with AJAX requests?

Looking at the code below, I am making two identical Ajax requests with only one line of difference. Is there a way to consolidate this into a function to maintain DRY (Don't Repeat Yourself) code? $('.searchable').multiSelect({ selecta ...

What could be causing the EBUSY: resource busy or locked, open errno: -4082 error to appear while trying to build storybook 7 in next.js 13?

While attempting to create a storybook, I encountered the following error in my project: [Error: EBUSY: resource busy or locked, open 'C:\Users\ali\Desktop\Works\Design Systems\projects\storybook-test2\node_modu ...

Retrieve information stored within an object's properties

Possible Duplicate: Accessing a JavaScript Object Literal's Value within the Same Object Let's take a closer look at this JavaScript object var settings = { user:"someuser", password:"password", country:"Country", birthplace:countr ...

The getStaticProps() function is failing to send data over to the components

I am currently learning how to use Next.js by following the guide on nextjs.org. My question is, when I use the getStaticProps function, it seems to fetch and log the data correctly inside the function. However, when I pass the data (which is the props ob ...