Obtain information from server-side data received from dynamically generated input fields


In my current situation, I have a text input field and a button that, when clicked, adds additional input fields to the page.
The JavaScript code I use to achieve this functionality is as follows:

    var myBtn = document.getElementById('myBtn');
    var qtyOfAdds = 0;
    myBtn.addEventListener('click', function (event) 
    {
        addField();
    });

    var form = document.getElementById('form1');

    function addField() 
    {
        var input = document.createElement('input');
        input.id = qtyOfAdds;
        input.name = qtyOfAdds;
        input.type = "Text";
        form.insertBefore(input, myBtn);
        qtyOfAdds++;
        document.getElementById('AddedFieldsCount').value = qtyOfAdds;
    }

On the server side, I retrieve post data to obtain all the input field data by using the following C# code:

var context = HttpContext.Current;
    List<string> fieldsList = new List<string>();
    string hiddenFieldData = context.Request["AddedFieldsCount"];
    int addedFieldsCount = 0;
    Int32.TryParse(hiddenFieldData, out addedFieldsCount);
    for (int i = 0; i < addedFieldsCount; i++)
    {
        fieldsList.Add(context.Request[i.ToString()]);
    }

This is how the HTML looks on the .aspx page:

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<link href="StyleSheet.css" rel="stylesheet" />
<script src="JavaScript.js"></script>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title></title>
</head>

<body>
    <form id="form1" runat="server">
    <input type="text"/>
    <button type="button" id="myBtn">ADD</button>
        <asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Submit" />
        <br />
        <input id="AddedFieldsCount" name="AddedFieldsCount" type="hidden" />
    </form> 
    <script src="JavaScript.js"></script>

</body>
</html>

Can you suggest a better way to handle this scenario?

Answer №1

If I were to tackle this situation with jQuery and Asp.Net MVC, my approach would be the following (please note that this code is untested and may contain errors). Additionally, it's important to know what purpose the text boxes will serve and what type of input they will accept.

On the client side:

$(document).ready(function(){
    $('#myBtn').click(function(){
        var $this = $(this),
            $form = $('#form1'),
            $inputs = $('input.tb');
            $newInput = $('<input/>', { type: 'text', name: 'tb' + $inputs.length, class: 'tb' }),

        $inputs.last().after($newInput);
   }
});

On the server side:

HttpContext context = HttpContext.Current;
// Retrieve all keys
List<string> keys = from key in context.Request.Form.AllKeys
                    where key.StartsWith("tb")
                    select key;

It's important to consider your specific requirements and desired outcome when implementing a solution. While your current method may work fine, the approach outlined above could also be utilized.

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

Error: Mocha Scope Function Undefined

Currently, I am following some TTD tutorials with Javascript and facing what appears to be a Javascript issue rather than a TTD problem. Here are the tests I have: 'use strict'; var chai = require('chai'); var expect = chai.expect; va ...

Angular 2 integration for Oauth 2 popup authorization

I am in the process of updating an existing Angular application to utilize Angular 2. One challenge I am facing is opening an OAuth flow in a new pop-up window and then using window.postMessage to send a signal back to the Angular 2 app once the OAuth proc ...

The issue of white space appearing in the first option of an AngularJS dropdown in Internet Explorer 11

<select id="selectIdentity" name="selectIdentity" required ng-trim="true" ng-change="changedValue(addUser.identityProvider)" ng-model="addUser.identityProvider" > <option value="" selected hidden /> <option ng-repeat="idprovid ...

Difficulty with ASP.net and Regional/Language Settings (Windows 2003)

Within an Asp.net form, there is a TextBox that utilizes a simple JavaScript function to separate each group of three digits entered into the TextBox. The script works flawlessly during data input, with commas serving as digit separators and periods as the ...

Creating a range using v-for directive in Vue

For example: range(3, 5) -> [3, 4] range(5, 10) -> [5, 6, 7, 8, 9] I am aware that we can generate range(1, x) using v-for, so I decided to experiment with it like this: // To achieve the numbers in range(5, 10), I set (10 - 5) on `v-for` // and t ...

Display a single button on hover in Angular 2+ framework

I'm looking to have the 'Edit' button only appear when I hover over a selected row. Here's the code: https://stackblitz.com/edit/inline-edit-change-edit2-j8b2jb?file=app%2Fapp.component.html I want the 'Edit' button to show u ...

In an effort to organize a roster of student roll numbers for the class, I am utilizing a JavaScript function to generate and update an array with the most recent entries

Greetings! I am looking to enhance the functionality of my webpage by allowing users to input the name and roll number of a new student. Once submitted, I want to add this student to an existing list using Javascript functions, for loops, and arrays, and d ...

Utilize mapping function to merge arrays

Currently facing an issue with no clear solution in sight. When making API calls via a map, I am able to successfully log all results individually. However, my challenge lies in combining these results into a single array. var alpha = ['a', &apo ...

Why is it that the "await" keyword lacks the ability to truly await?

I created this code to access the google calendar API and retrieve information. To make it easier to understand, I added the variable x to the function. Initially, I expected x to be displayed as 1, however, it consistently shows up as 1. The main issue ...

Determine the specific table entry that was clicked on

Currently, I am working on developing a dynamic table that includes a button in one of its columns, which triggers a bootstrap modal. I'm a bit unsure on how to determine which button was clicked and how to populate the table accordingly. Admittedly, ...

Is the Site Header displayed depending on the scroll position and direction of scrolling?

On my website, I have a header that I want to hide when the user scrolls down 100px and show again when they scroll up 50px. I attempted to write a script for this functionality, but it doesn't seem to be working as expected. CSS /* This CSS rule w ...

I can only use innerHTML once in my React application

I am attempting to clear my container div when the user clicks the search button in order to remove all existing search results. However, I am encountering an issue where using innerHTML to clear the container div only works the first time. If a second sea ...

Encountering the error message "{error: 'Operation `users.findOne()` buffering timed out after 10000ms'}" while trying to access my app on localhost

In my project, I have organized my code into 'client' and 'server' folders. The server side of the application is built using Express and successfully connected to a MongoDB database in the server folder using nodemon. https://i.sstati ...

Looking for the properties of the ServerResponse object in node.js - where can I locate them?

Currently, I've been diving into the book Node.js In Action. Chapter 9 introduces a message module with a function that has left me puzzled about the 'this' object when calling res.message. To gain clarity, I decided to print out the name of ...

Exploring the process of building a JavaScript function inside a JSON object using Gson

Can Gson generate JSON that includes a JavaScript function without a key nested within? { autosave: { save( editor ) { return editor.saveData( editor.id, editor.getData() ); }, waitingTime: 2000 } Appreciate any hel ...

Using HTML5 Canvas with Firefox 4: How to Retrieve Click Coordinates

Lately, I've been diving into creating HTML5 Video and Canvas demos. Initially, my focus was on optimizing them for Chrome, but now I'm shifting my attention to Firefox and Safari as well. One particular demo I'm currently working on involv ...

Having trouble utilizing props with Vue axios? Running into an undefined error? Unsure how to properly use props with axios?

https://i.stack.imgur.com/QfCDG.png There seems to be an issue with my saveComment() function in CommentList.vue. It can't find the comments' post_id and causes this error: CommentList.vue?6c27:107 Uncaught TypeError: Cannot read properties of u ...

Storing Redux state in local storage for persistence within a React application

Recently, I've been experimenting with persisting data to local storage using Redux. My approach involved creating an array of alphabet letters and setting up an event listener to log a random letter each time it's clicked. However, despite succe ...

displaying several gltf 3D models simultaneously on a map using mapbox gl and three js

Recently, I encountered an issue with adding glTF 3D models to a map using Mapbox GL and Three.js. It seems that while I can successfully add a single glTF model in a separate layer on the map, I am facing difficulties when trying to add multiple glTF mode ...

Instructions for converting a readonly text field into an editable one using JavaScript

I'm trying to make it so that when the button (with id name_button) is clicked, the text field (with id name_text_field) becomes enabled. However, my current code doesn't seem to be working. Here's a snippet of my HTML: <input type="tex ...