Sending dynamic modal form fields to django: A step-by-step guide

When creating a dynamic modal form field, only one field value is being sent to my Django server. I suspect this may be due to the input fields having the same name. Any suggestions on how to fix this issue?

   <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <script>
    $(document).ready(function() {
var max_fields = 10;
var wrapper = $(".container1");
var add_button = $(".add_form_field");

var x = 1;
$(add_button).click(function(e) {
    e.preventDefault();
    if (x < max_fields) {
        x++;
        $(wrapper).append('<div><input type="text" name="mytext[]"/><a href="#" class="delete">Delete</a></div>'); //add input box
    } else {
        alert('You Reached the limits')
    }
});

$(wrapper).on("click", ".delete", function(e) {
    e.preventDefault();
    $(this).parent('div').remove();
    x--;
})

});

                      <div class="modal fade" id="multipleset{{ecriture.id_ecriture}}" tabindex="-1" role="dialog" aria-labelledby="edit" aria-hidden="true">
                             <div class="modal-dialog" role="document">
                                <div class="modal-content">
                                   <div class="modal-header">
                                      <h6 class="modal-title" id="exampleModalLabel">Ajouter une &eacute;criture</h6>
                                      <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                                      <span aria-hidden="true">&times;</span>
                                      </button>
                                   </div>

                                  <form action="{% url 'multipleset' %}" method="post" enctype="multipart/form-data">{% csrf_token %}
                                    <div class="modal-body">
                                      <div class="container1">
                                          <button class="add_form_field">Add New Field &nbsp;
                                            <span style="font-size:16px; font-weight:bold;">+ </span>
                                          </button>
                                          <div><input type="text" name="mytext[]"></div>
                                      </div>
                                    </div>
                                    <div class="modal-footer">
                                      <button type="button" class="btn btn-secondary" data-dismiss="modal">Fermer</button>
                                      <button type="submit" class="btn btn-primary">Ajouter</button>
                                    </div>
                                  </form>
                                </div>
                             </div>
                      </div>

Answer №1

To make the input name change dynamically, you can follow the example below. This should work effectively. (Not tested yet) Feel free to give it a try.

$(wrapper).append('<div><input type="text" name="mytext'+x+'"/><a href="#" class="delete">Delete</a></div>'); //add input box

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

Display a pdf stream within a fresh window

I have a PDF document generated on the server that I need to display on the client side. The code on the server looks like this: ByteArrayOutputStream baos = generatePDF(); response.setContentType("application/pdf"); response.setHeader("Content-Dispositio ...

Customize the keyboard on your iPod by replacing the default one with a

Looking to customize the iPOD keyboard to only display numbers, similar to a telephone keypad: https://i.stack.imgur.com/X0L3y.png The current iPOD default keyboard looks like this: https://i.stack.imgur.com/VykjU.png ...

What is the best way to invoke a function with multiple parameters in TypeScript?

I have a function that manipulates a specified query string, along with another version that always uses window.location.search. Here is the code snippet: class MyClass { public changeQuery(query: string; exclude: boolean = true; ...values: string[]): st ...

Implement a select element with an onchange event that triggers an AJAX

As a newcomer to Javascript, I've been struggling to find a solution to my issue. The goal is to add an additional select option when the previous select option is changed. I attempted to implement the code below, but it's not functioning correct ...

Access a JSON value in the Google Sheets script editor and retrieve the data

I'm trying to retrieve a value from a JSON object by making an API call in a Google Sheet. Below is the script I am using: function getBitcoinPrice() { var url = "https://acx.io//api/v2/tickers/btcaud.json"; var response = UrlFetchApp.fetc ...

The error states that the type '() => string | JSX.Element' cannot be assigned to the type 'FC<{}>'

Can someone help me with this error I'm encountering? I am fairly new to typescript, so I assume it has something to do with that. Below is the code snippet in question: Any guidance would be greatly appreciated. const Pizzas: React.FC = () => { ...

Using Javascript to dynamically add and remove elements on click

Whenever I click on a link, I am able to generate input, label, and text. However, I want to be able to delete these elements with the next click event on the same link: I've tried updating my code like this: var addAnswer = (function() { var la ...

How to extract a variable from a mongoose find method in a Node.js application

Within my Node.js program, I utilize my Mongoose database to query for a specific value in a collection, of which there is only one value present. var myValueX; myCollection.find(function(err, post) { if (err) { console.log('Error ...

Implementing a permanent class following an incident

Is it possible to dynamically add a class to an element when an event occurs rather than based on a condition? For example, I have a td that displays a variable. <td>{{myVar}}</td>//myVar=10 When the variable changes to myVar=15, I want to ad ...

The local authentication feature in NodeJS Passport is experiencing issues and not functioning properly

I have integrated passportjs local for authentication. However, I am facing an issue where it always redirects to the failureRedirect without displaying any error messages. The redirect also includes the original username and password, resulting in a dupli ...

Using regular expressions in JavaScript to work with numbers separated by commas, as well as their comparison operators such as greater than, greater than or

Currently, I have implemented this Regex pattern to validate numbers with decimals (comma separated) /(^\d*\,?\d*[1-9]+\d*$)|(^[1-9]+\d*\,\d*$)/ However, I am now faced with the need to modify it in order to also valida ...

Adding custom script bundles in NextJS is a great way to enhance the functionality and

I am facing a challenge with incorporating legacy custom JavaScript files into my project. These scripts need to be bundled and linked in the _document.js file with a hash included in the filename. What is the most effective approach to achieve this? I h ...

Showing information from a database while incorporating line breaks with the help of nl2br

Having trouble with the previous question, so I'll provide more detail here. Below is my index.php file where I explain the method used to save data to a database. <html> <head> <script> function updategroup() { var update_c ...

Is there a way to display both the label and the input field in a single line?

How do I align the label and input on the same line with a spacing of 1.5cm between them? I tried using this resource, where it mentioned using form-inline but wasn't successful in achieving the desired layout. https://i.sstatic.net/7MW2H.png Appre ...

New post: "Exploring the latest features in Angular

Looking for help with integrating Angular and SpringREST to fetch data from the backend? Here's my situation: I need to retrieve a JSON string from the backend using a POST request, send it to my site's hosted link, and display it on the user int ...

Is there a way to retrieve the objects generated by DirectionsRenderer on Google Maps V3?

Is there a simple method to access the objects and properties of the markers and infowindows that are generated by the DirectionsRenderer? (such as the "A" and "B" endpoints of the route) I want to swap out the infowindows for the "A" & "B" markers wi ...

Discovering duplicates for properties within an array of objects in React.js and assigning a sequential number to that specific field

I am working with an array of objects where each object contains information like this: const myArr=[{name:"john",id:1}{name:"john",id:2}{name:"mary",id:3}] In the first 2 elements, the "name" property has duplicates with the value "john". How can I updat ...

What could be causing certain JS files to fail to load in HTML?

I'm facing an issue with loading multiple JavaScript files in my HTML code. Only the jQuery file is loading, while the other two files are not. Could someone please help me identify the mistake I am making? When I check the network tab using the inspe ...

Retrieve information from a JSON file by utilizing the JSON file itself as a variable

Currently, I am attempting to extract the URL of an attached photo using JSON. I am utilizing the value of the data from the JSON key "HousePhoto1" to then access the value from the post_media data. The issue I am encountering is that my JavaScript code fa ...

Tips on retrieving objects from Firebase's item Array

Although I've searched for similar questions, I can't seem to find the right solution to my issue. I've been working on a firebase / vue.js project as a training exercise where I'm refactoring it to incorporate Vuex, http vue resource c ...