Retrieve the value of a dynamically generated input element within a form object

I'm trying to figure out how to reference a dynamic 'name' of an input element in a form. Can anyone help?

Here's an example using HTML:

<form>
    <input type="text" name="qty1" value="input1" />
     <input type="text" name="qty2" value="input2" />
     <input type="text" name="qty3" value="input3" />

    <input type="submit" value="Submit" onClick="checkVal(this.form); return false;" />
</form>

Now, I have some Javascript that isn't working:

function checkVal(form) {
    for (var i = 1; i <= 3; i++) {
        alert(form.qty+i.value);  // Struggling with this line..
    }
}

When running the above javascript, it outputs NaN. Any idea how to properly reference qty1, qty2, and qty3 inside a for loop using the variable i?

Check out my jsfiddle here for more context: http://jsfiddle.net/MRzWf/

Answer №1

Learn about Using bracket notation

 form["qty" + index].value

function validateQuantity(form) {
    for (var index = 1; index <= 3; index++) {
        console.log("qty" + index, form["qty" + index].value);
    }
}
<form>
    <input type="text" name="qty1" value="input1" />
    <br/>
    <input type="text" name="qty2" value="input2" />
    <br/>
    <input type="text" name="qty3" value="input3" />
    <br/>
    <input type="submit" value="Submit" onClick="validateQuantity(this.form); return false;" />
</form>

Answer №3

The issue lies in the code snippet form.qty+i.

In order to access an element within an array, you need to use the index inside the parentheses.

Alternatively, you can check the value of input fields using the following function:

function checkVal(form) {
    var allInputs = document.getElementsByTagName('input');
    for (var i = 0; i < 3; i++) {
          if(allInputs[i].type == 'text'){
                alert(allInputs[i].value);  
          }
    }
}

View DEMO

Answer №4

Regular Solution

Utilizing: form.elements[] should be compatible with all web browsers.

function validateInput(form) {
    for (var index = 1; index <= 3; index++) {
        alert(form.elements["quantity"+index].value);

        /* Alternatively, using a dynamic name variable
        var elementName = "quantity"+index;
        alert(form.elements[elementName].value);
        */
    }
}

Answer №5

Give this a shot. It should solve the issue mentioned earlier

function verifyInputValues(form) {
for (var i = 0; i < 3; i++) {
    alert(document.getElementsByTagName("input")[i].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

Other options besides re-flowing and repainting

After doing some research on various platforms like Stack Overflow, I've come across information stating that re-paints and re-flows can be quite taxing on a browser's resources. I am interested in learning about alternative CSS/JS techniques to ...

Gensim's Word2Vec is throwing an error: ValueError - Section header required before line #0

Hello everyone! I am diving into the world of Gensim Word2Vec and could use some guidance. My current task involves using Word2Vec to create word vectors for raw HTML files. To kick things off, I convert these HTML files into text files. Question Number O ...

Unable to specify the width of my website using full-width in Bootstrap

Using the bootstrap grid system has caused a slight issue for me. Whenever I scroll to the right side of the window, there is a white space that appears: I have set the body width as 100vw; Is there a way to eliminate this unwanted space? ...

What is the relationship between font size adjustments and the dimensions of the surrounding parent div element?

I've come across an issue that involves having the following code snippet in the body of an HTML file: html, body { width: 99%; height: 99%; margin: 0px; overflow: hidden; } #container1 { display: flex; gap: 2%; width: 90%; heigh ...

Sending an image via email using a highly limited HTML interface

I am working on setting up a webpage connected to my company's internal Intranet page that is specifically designed to allow an iPad to take a picture and then email the picture using our webmail application. The current HTML code I have only allows m ...

I'm having trouble retrieving my variable within the socketcluster's socket.on function

How can I store the value of msg in the variable sample when sample is not accessible inside the callback function? import { Injectable } from '@angular/core'; import * as socketCluster from 'socketcluster-client'; @Injectable({ pro ...

Why is this regular expression failing to match German words?

I am attempting to separate the words in the following sentence and enclose them in individual span elements. <p class="german_p big">Das ist ein schönes Armband</p> I came across this: How to get a word under cursor using JavaScript? $(&ap ...

Implementing a function to navigate to a different page using jQuery mobile

I'm attempting to pass a function when changing pages in jQuery Mobile, but I keep getting an error that points to `$.ajax` $( ":mobile-pagecontainer" ).pagecontainer( "change", "#schoolperformance", { reload : true, showLoadMsg : false, ...

Tips for Providing Real-Time Data for a Dynamic Chart in d3

I have a line chart sample from D3, and the issue I'm facing is that I need to continuously feed live data from a server at certain time intervals and use D3 to draw the chart based on this dynamic data. Despite my efforts to search for a solution, I ...

Gaining entry to specialized assistance through an occasion

Having trouble accessing a custom service from a custom event. Every time the event is fired, the service reference turns out to be null. @Component({ selector: "my-component", template: mySource, legacy: { transclude: true } }) export class myComponent { ...

The HTML table fails to refresh after an Ajax request has been made

I am currently utilizing Ajax to delete a row from the Roles table. The functionality allows the user to add and delete roles using a link for each row. While the deletion process works properly and removes the row from the database, the table does not get ...

What is the best way for a background-image to determine its height in CSS?

I am currently working on a website project and I would like to include my title using a background-image because it uses a unique font. In my design class, we were taught that this is the best approach. However, I am struggling with setting the correct di ...

Decapitalizing URL string in jQuery GET request

Check out my code below: $.get('top secret url and stuff',function(data){ console.log($("[style='color:white']", data.results_html)[0].innerHTML); window.html = document.createElement('d ...

Encountering issues importing Ace Document Object in a Vue webpack project?

In my Vue and Webpack project, I am trying to incorporate the Ace editor. My goal is to associate each file with a single instance of an Ace Document. To achieve this, I followed the default import method: import Ace from 'ace-builds' When atte ...

Exploring the power of async/await in conjunction with loops

My JavaScript code is designed to extract content from HTML pages and perform a crawling operation. However, the issue arises with asynchronous execution due to a request function. I attempted to utilize Promises and async & await to address this probl ...

Choose an option from a dropdown menu and assign it to a JavaScript variable

Is it possible to store the selected option from a dropdown list as a JavaScript variable, even when new Ajax content is loaded on the page? Below is a simple form code example: <form name="searchLocations" method="POST"> <select name="l ...

What is the best way to fetch a partial JSON response object from an API using JavaScript?

Currently, I am utilizing the One Bus Away API, returning a response object in this format: { "code": 200, "currentTime": 1504150060044, "data": { "entry": { "arrivalsAndDepartures": [ {AnD_item1 ...

Executing functionality based on changes in Angular bindings

I am working on securing user passwords in my HTML form. Currently, the password field is stored in localstorage like this: In JS: $scope.localStorage = localStorage; And then in HTML: <input id="pass" type="password" ng-model="localStorage.pass" re ...

Why is it necessary in JavaScript to reset the function's prototype after resetting the function prototype constructor as well?

Code is often written in the following manner: function G() {}; var item = {...} G.prototype = item; G.prototype.constructor = G // What is the purpose of this line? Why do we need to include G.prototype = item before resetting the prototype? What exact ...