The HTML <form> codes that I try to append using JavaScript are not being recognized in my View

var counter = 1;
$(function () {
    $('#addDonation').click(function () {
        $('<div class="card border-apoio mb-3" id="cardDonation' + counter + '">' +
              '<div class= "card-body" >' +
                   '<div class="row">' +
                       '<div class="form-group col-3">' +
                           '<label asp-for="@Model[' + counter + '].Type"><strong>Tipo:</strong></label>' +
                           '<select asp-for="@Model[' + counter + '].Type" class="form-control">' +
                               '<option value="Alimento">Alimento</option>' +
                               '<option value="Brinquedo">Brinquedo</option>' +
                               '<option value="Roupa">Roupa</option>' +
                           '</select>' +
                        '</div>' +

                        '<div class="form-group col-5">' +
                            '<label asp-for="@Model[' + counter + '].Name"><strong>Nome:</strong></label>' +
                            '<input asp-for="@Model[' + counter + '].Name" placeholder="Nome ou descrição genérica" class="form-control" />' +
                        '</div>' +

                        '<div class="form-group col-1">' +
                            '<label asp-for="@Model[' + counter + '].Quantity"><strong>Quantidade:</strong></label>' +
                            '<input asp-for="@Model[' + counter + '].Quantity" value="1" class="form-control" />' +
                        '</div>' +

                        '<div class="form-group col-2">' +
                            '<label asp-for="@Model[' + counter + '].UnitsMeasure"><strong>Unidade de Medida:</strong></label>' +
                            '<select asp-for="@Model[' + counter + '].UnitsMeasure" value="Unidades" class="form-control">' +
                                '<option value="Unidade(s)">Unidades</option>' +
                                '<option value="KG">Quilograma(s) (KG)</option>' +
                                '<option value="L">Litro(s) (L)</option>' +
                            '</select>' +
                        '</div>' +
                        '<div class="col-1">' +
                            '<button type="button" class="btn" onclick="removeCard(' + counter + ');"><span class="bi bi-trash icon-size-2"></span></button>' +
                        '</div>' +
                   '</div>' +
               '</div >' +
        '</div >').appendTo('#cardDonations');
        counter++;
        return false;
    });
});
function removeCard(index) {
    if (counter > 1) {
        $('#cardDonation' + index).remove();
        counter--;
    }
    return false;
}
@model List<Donation>;

<div class="text-center">
    <h1>Doações</h1>
</div>

<form asp-action="Doacoes" method="post">
    <div asp-validation-summary="All"></div>

    <div id="cardDonations">
        <div class="card border-apoio mb-3" id="cardDonation0">
            <div class="card-body">
                <div class="row">
                    <div class="form-group col-3">
                        <label asp-for="@Model[0].Type"><strong>Tipo:</strong></label>
                        <select asp-for="@Model[0].Type" class="form-control">
                            <option value="Alimento">Alimento</option>
                            <option value="Brinquedo">Brinquedo</option>
                            <option value="Roupa">Roupa</option>
                        </select>
                    </div>

                    <div class="form-group col-5">
                        <label asp-for="@Model[0].Name"><strong>Nome:</strong></label>
                        <input asp-for="@Model[0].Name" placeholder="Nome ou descrição genérica" class="form-control" />
                    </div>

                    <div class="form-group col-1">
                        <label asp-for="@Model[0].Quantity"><strong>Quantidade:</strong></label>
                        <input asp-for="@Model[0].Quantity" value="1" class="form-control" />
                    </div>

                    <div class="form-group col-2">
                        <label asp-for="@Model[0].UnitsMeasure"><strong>Unidade de Medida:</strong></label>
                        <select asp-for="@Model[0].UnitsMeasure" value="Unidades" class="form-control">
                            <option value="Unidade(s)">Unidades</option>
                            <option value="KG">Quilograma(s) (KG)</option>
                            <option value="L">Litro(s) (L)</option>
                        </select>
                    </div>
                    <div class="col-1">
                        <button type="button" class="btn" onclick="removeCard(0);"><span class="bi bi-trash icon-size-2"></span></button>
                    </div>
                </div>
            </div>
        </div>
    </div>
    
    <div class="d-grid gap-2 mt-3">
        <button id="addDonation" type="button" class="btn btn-apoio-verde">
            <span class="bi bi-list-ol"></span>
            Adicionar Item
        </button>
    </div>
    
    <div class="text-center mt-3">
        <button type="submit" class="btn btn-apoio-laranja">
            <span class="bi bi-plus"></span>
            Adicionar Lista
        </button>
    </div>
    
</form>

This script enables the addition of multiple objects, represented by bootstrap cards, with a single click on the submit button. Instead of adding one object at a time, this functionality allows for the creation of multiple objects simultaneously based on the number of cards added through the JavaScript code.

The issue being faced is that only the first object is being created, and subsequent objects like @Model[1], @Model[2], and so on are not being recognized or generated by the view.

To resolve this problem, you may need to revisit how the counter variable from the JavaScript code is interacting with the HTML elements and ensure that each newly added object is properly indexed and associated with the corresponding Model data in your application.

Answer №1

    var count = 1;
$(function () {
    $('#addContribution').click(function () {
        $('<div class="card border-support mb-3" id="contributionCard' + count + '">' +
              '<div class= "card-body" >' +
                   '<div class="row">' +
                       '<div class="form-group col-3">' +
                           '<label for="[' + count + '].Type"><strong>Type:</strong></label>' +
                           '<select name="[' + count + '].Type" class="form-control">' +
                               '<option value="Food">Food</option>' +
                               '<option value="Toy">Toy</option>' +
                               '<option value="Clothing">Clothing</option>' +
                           '</select>' +
                        '</div>' +

                        '<div class="form-group col-5">' +
                            '<label for="[' + count + '].Name"><strong>Name:</strong></label>' +
                            '<input name="[' + count + '].Name" placeholder="Name or generic description" class="form-control" />' +
                        '</div>' +

                        '<div class="form-group col-1">' +
                            '<label for="[' + count + '].Quantity"><strong>Quantity:</strong></label>' +
                            '<input name="[' + count + '].Quantity" value="1" class="form-control" />' +
                        '</div>' +

                        '<div class="form-group col-2">' +
                            '<label for="[' + count + '].UnitsMeasure"><strong>Unit of Measure:</strong></label>' +
                            '<select name="[' + counter + '].UnitsMeasure" value="Units" class="form-control">' +
                                '<option value="Unit(s)">Units</option>' +
                                '<option value="KG">Kilogram(s) (KG)</option>' +
                                '<option value="L">Liter(s) (L)</option>' +
                            '</select>' +
                        '</div>' +
                        '<div class="col-1">' +
                            '<button type="button" class="btn" onclick="removeCard(' + count + ');"><span class="bi bi-trash icon-size-2"></span></button>' +
                        '</div>' +
                   '</div>' +
               '</div>' +
        '</div>').appendTo('#contributionCards');
        count++;
        return false;
    });
});
function removeCard(index) {
    if (count > 1) {
        $('#contributionCard' + index).remove();
        count--;
    }
    return false;
}

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

What is the best way to pass the value from one JavaScript file to another in the ViewModels and main JavaScript file?

https://i.sstatic.net/pzFAS.jpg Within the login.js file, a REST API is returning specific values that need to be utilized in the Dashboard.html file. However, the values are not being retrieved successfully in the dashboard.js file. A similar requiremen ...

What is the proper way to declare a JavaScript variable using a hyphen symbol?

When it comes to evaluating a string like employee-count = 3, my main issue arises when dealing with variables that may not have a standard naming convention. While valid variable names pose no challenge, identifiers such as employee-count leave me slightl ...

I want to retrieve a complete HTML page using an AJAX request

I am trying to retrieve the content of a specific page, but encountering issues when using this function: function getResult() { var url="http://service.semanticproxy.com/processurl/ftfu27m3k66dvc3r43bzfneh/html/http://www.smallbiztechnology.c ...

Using multiple onChange and value attributes in React to handle different input fields and

I am having trouble setting a maximum input value in a text field, and I can't seem to figure out how to make it work. The issue seems to be with the two onChange events and values. I'm not sure how to resolve this. function Form({ onAddStudent ...

The Microsoft Jet database is unable to access the file '...'. It has been opened exclusively by another user or you do not have the necessary permissions to view its contents

I recently inherited a WinForms application that was developed using Visual Studio 2005 with VB.Net and relies on an Access database. The application functions perfectly when installed as a standalone version, however, I am encountering issues with the net ...

I'm having trouble locating the default layout in VUE 3

Upon exploring Vue 2, I came across a folder named /layouts, containing a default template that gets rendered for all Vue views. In Vue 3, I couldn't locate the same folder. After doing some research, I discovered the existence of the .nuxt/ folder, ...

How to seamlessly upload an image in PHP without the need to refresh the page

Can anyone provide guidance on how to upload an image without having to refresh the page? I have been searching for solutions but haven't found a suitable one yet. ...

Using Dropzone.js to bypass the Browse dialog when uploading files in integration tests with php-webdriver

Currently, I am implementing dropzone.js in my project. I have a specific requirement where I need to manually add a file to the queue without triggering the file browser dialog box. The dropzone has been initialized on the element with the class .imageDro ...

Issue with Chrome extension's popup not displaying

I was developing a chrome extension, but I encountered an issue where the popup does not display when clicking on the icon. After researching online, I found suggestions to change page_action to browser_action. However, even after making this adjustment, ...

Having trouble retrieving the response from Jquery ajax with ajaxoptions

Struggling to utilize jQuery effectively. function fetchData(Id) { var ajaxOptions = { url: 'Api/Client/Get?Id=' + id, type: 'GET', dataType: 'json' }; return $.ajax(ajaxOptions).done().fa ...

Clear form values in react-hook-form upon form closure

Featuring the given component: import { yupResolver } from '@hookform/resolvers/yup'; import { useForm } from 'react-hook-form'; import * as yup from 'yup'; import { useToggle } from '../shared/hooks'; import { Su ...

Exploring the Potential of Using Client-Side Includes with JavaScript/jQuery

Are there techniques for organizing javascript/jquery code in a manner similar to server-side include() script concatenation in PHP? I have an extensive javascript engine embedded with dynamic code sourced from my database. I am looking to segregate the ...

What is the method for calculating the difference in days between two Jalali dates when selecting the second date picker input?

I have integrated the Persian Datepicker script from GitHub to display jalali dates on my webpage. Users can select date1 and date2 from the datepicker to input their desired dates. Below is the code snippet: $(document).ready(function() { $('. ...

I attempted to utilize Ajax to invoke my PHP function, but I'm having trouble pinpointing the issue as the code doesn't seem to be functioning correctly

!-- Welcome to the Main Page -- <section class="container"> <div class="row"> <div class="centerlogin"> <div class="frmlogin"> <form role="form" name="signin" id="signin" method="post" action="#"> ...

Background of Google Maps HeatmapLayer

After creating heatmapLayers, I've noticed a strange issue where adding and removing them affects the background color of the entire map component, even in areas with no data points nearby. The extent of this background change is determined by the alp ...

Identify instances of repeated values in input fields

I'm working on a complex html form that includes multiple email fields. To ensure data integrity, I want to prevent users from entering the same email in more than one field. After some trial and error, I successfully identified duplicate emails by s ...

What is the simplest method in C# for determining if an application is running from a network drive?

Is there a straightforward way to determine if my application is being run from a network drive programmatically? The solution should cater to both UNC paths (\\127.0.0.1\d$) and mapped network drives (Z:). ...

Attempting to grasp the concept of memory leakage in a more thorough manner

As I dive into the world of frontend development and start learning Vue.js, I came across a paragraph in the tutorial that caught my attention: Vue.js makes rendering a template seem simple, but under the hood it does a lot of work. The data and DOM are ...

Decrease the construction duration within a sprawling Angular 8 project

It takes nearly 10-15 minutes to compile the project in production mode, resulting in a dist folder size of 32MB Here are the production options I am currently using:- "production": { "optimization": true, "outputHashing": "all", ...

Ways to display fresh information on webpage following data preservation in AngularJS

After saving some names in a form, I am attempting to display them alphabetically. Below is the method that contains all the saved data. The variable response.data should contain this data: function refreshNames() { NameService.getNames().then(func ...