Issue with Submit Button Functionality in Django Form Submission

I'm currently facing an issue with an HTML template I built using Bootstrap. My problem lies in the fact that I have a JavaScript function that dynamically adds rows to a Django form with specific fields whenever I need to. However, when I add a row, the submit button ceases to function as intended and instead keeps adding more product fields that need to be filled, all initialized to "None."

Here is the code snippet for the HTML template:

{% block createlist %}
  
  <form id="form-container" method="POST">
      {% csrf_token %}
      <div class="card">
          <div class="form-group" id="form-group">
              
              <div class="row mt-3">
                  
                  <h4 class="card-title md-2 m-2">List Name</h4>
                  <div class="m-2">{{ listform.name}}</div> 
              </div>
  
              <div id="button_row" class="row mt-0 no-gutters"> <!-- Apply .row class here -->
                  <div class="row">
                      <h2 class="col-md-2  md-2 m-2">Products</h2>
                      <div id="add-form" class="col-md-1 md-2 m-2"><button  type="button" class="btn btn-primary">+</button></div>
                  </div>
                  
                  <div class="col-md-2 m-2">Product Name</div> 
                  <div class="col-md-2 m-2">Quantity</div>
                  <div class="col-md-2 m-2">Weight</div>
                  <div class="col-md-2 m-2">Price</div>
  
              </div>
              {{ productformset.management_form }}
              {% for form in productformset %}
              <div id="form-row" class="row mt-0 no-gutters"> <!-- Apply .row class here -->
                  <div class="col-md-2 m-2"><input type="text" name="{{ form.prefix }}-product_name" value=""></div> 
                  <div class="col-md-2 m-2"><input type="text" name="{{ form.prefix }}-quantity" value="{{ form.quantity.value }}"></div>
                  <div class="col-md-2 m-2"><input type="text" name="{{ form.prefix }}-weight" value="{{ form.weight.value }}"></div>
                  <div class="col-md-2 m-2"><input type="text" name="{{ form.prefix }}-price" value="{{ form.price.value }}"></div>
              </div>
              {% endfor %}
              
            
          </div>
          
      </div>
      <button type="submit">Submit</button>  
  </form>
  <script>
      document.addEventListener("DOMContentLoaded", function() {
          let addButton = document.querySelector("#add-form");
          let totalForms = document.querySelector("#id_form-TOTAL_FORMS");
          let productFormRowToClone = document.querySelector("#form-row");
          let productFormsContainer = document.querySelector("#form-group");
  
          let formNum = productFormRowToClone.children.length - 2;
          addButton.addEventListener('click', addForm);
  
          function addForm(e) {
              e.preventDefault();
              
              let newProductFormRow = productFormRowToClone.cloneNode(true); // Clone the specific row
  
              // Increment form number 
              // Exclude the header row
              formNum++;
              
              // Update the form prefixes
              let formRegex = RegExp(`form-(\\d){1}-`, 'g');
  
              newProductFormRow.innerHTML = newProductFormRow.innerHTML.replace(formRegex, `form-${formNum}-`)
  
              // Insert the new form before the submit button
              productFormsContainer.insertAdjacentElement("beforeend",newProductFormRow);
  
              totalForms.setAttribute('value', `${formNum+1}`);
          }
      });
  </script>
  {% endblock createlist %}
  

Below is a screenshot of the issue I'm facing. When I click the submit button, rows with "None" values keep getting added: enter image description here

I've made various changes to the JavaScript file but haven't been able to pinpoint the exact cause of the problem. Previously, when the add button wasn't inside a div with the class "row" but was directly under the whole container, it worked fine.

Answer №1

Your issue lies within the logic you are using to count the number of forms. Initially, your variable is set up like this:

let formNum = productFormRowToClone.children.length - 2;

The element with the ID form-row is referred to as productFormRowToClone in your code. This particular element, based on the HTML structure, contains 4 form inputs. Therefore, formNum will always start at 2. Upon calling addForm, it increments to 3 and sets the input id_form-TOTAL_FORMS to 4. Subsequently, when you submit the form, Django returns it with errors.

To resolve this, consider adding a class to the form row div and utilize it for counting the forms:

<div id="form-row" class="row mt-0 no-gutters form-row">

Adjust the form counting logic to:

let formNum = document.querySelectorAll(".form-row").length - 1

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

tips on incorporating chosen while still enabling text input

I am currently utilizing chosen to showcase a single selection from a lengthy array of choices. In addition, I am seeking the functionality to enable users to submit a choice that is not listed among the available options. This customization is specifica ...

Exploring the isolated scopes of AngularJS directives

Exploring directives in AngularJS led me to this interesting code snippet: var app = angular.module('app', []); //custom directive creation app.directive("myDir", function () { return { restrict: "E", scope: { title: '@ ...

"Mastering the art of debouncing in Angular using

I am facing an issue where, during a slow internet connection, users can press the save button multiple times resulting in saving multiple sets of data. This problem doesn't occur when working locally, but it does happen on our staging environment. E ...

Navigating through an object using both dot and bracket notation

Can anyone shed some light on why I keep getting an 'undefined' message when trying to access object properties using dot notation like return contacts[i].prop;? However, if I use bracket notation like return contacts[i][prop];, it works fine an ...

Having trouble with NextJS not updating state upon button click?

I am encountering a problem with my NextJS application. I am attempting to show a loading spinner on a button when it is used for user login. I have tried setting the `loading` state to true before calling the login function and then reverting it to fals ...

Having trouble with HTML tags not parsing correctly in PHP?

Similar Question: Getting a parse error: syntax error, unexpected T_STRING 59 I'm working on displaying names from a database in a table format with checkboxes. Everything seems to be functioning correctly until I try to include the input tag wit ...

Struggling to design a button that can delete tasks from the list, but encountering issues with the filter function

Although I am able to push values, I seem to be struggling with the filtering process. Can anyone provide guidance on whether I am using the filter method incorrectly or if there is another issue at play? import { useState } from 'react'; const ...

What is the method for creating a function using the const keyword in JavaScript?

I trust you are doing well. Recently, I have embarked on a coding journey and encountered an interesting challenge. The task requires me to create a function that outputs specific weather conditions for different countries to the console: The weather in ...

Obtaining a value from an array using Google App Script

Having some difficulties with the code snippet provided here. It might be a basic question, but I'm unable to figure out what's going wrong. The issue is that I'm trying to perform calculations on individual values in an array generated fro ...

Subclassing Observable in RxJS 5: Parent class instances are returned by static methods

I've been experimenting with subclassing the RxJS Observable class and overriding the lift method, as explained here. While I can successfully add new operators to the prototype, when trying to create a new Observable using my subclass (such as MyObs ...

Changing JavaScript functions into jQuery functions

Currently, I have this Javascript function that I am interested in converting to jQuery: function confirm() { var http = new XMLHttpRequest(); var url = "index.php?tag=' . $dt . '"; var params = "confirm_ref=' . urlencode(encry ...

Using the onClick event to dynamically alter the class name within a mapped array by leveraging Hooks

I'm currently working on developing an answer sheet, commonly known as a "Bubble sheet", where the user has the ability to select either "A,B,C, or D" and see the bubble transition from light mode to dark mode just like when marking with a physical pe ...

Swap an iframe for an image pulled from the iframe's URL using jQuery

My plan is to create a variable by extracting an attribute's value in order to add a new object using that variable as the value of another attribute... In my media search site, I am working with a restricted environment where I cannot fully configur ...

CSS dropline menu

I am working on customizing a CSS dropdown menu for my website. My goal is to have the homepage aligned to the left side of the page instead of the center. Below is the style sheet and the div tags I am using for the dropdown navigation bar: ul, li, htm ...

Form using Ajax technology, including two drop-down menus sourced externally

Is there a way to automatically populate a second drop-down list with all models once a selection is made in the first drop-down on a form? Below is the code snippet: <form> <div class="landing_quote_left"> ...

How can Angular CLI prevent the submission of an HTML form unless a previous option has been selected

I am currently working on a form that contains select fields with various options pre-populated. <form [formGroup]="selectVehicleForm"> <select formControlName="Manufacturer"> <option *ngFor='let ...

Ensure that an input field on the PHP form is required

Currently working on a form with multiple input fields. I'm wondering if there's a way to prevent the form from being submitted to the server if a specific field is left empty. I'd like to use a JavaScript pop-up box to notify the user inst ...

Problem with transferring data from Google Forms to Google Sheets using Google Apps Script

Currently, I am having an issue with my code that adds responses to a Google Sheets from a Google Forms sheet. The problem is that it always adds the responses to the first column, even if it should go into a different column based on its title. I suspec ...

Angular - Detecting Scroll Events on Page Scrolling Only

I am currently working on implementing a "show more" feature and need to monitor the scroll event for this purpose. The code I am using is: window.addEventListener('scroll', this.scroll, true); Here is the scroll function: scroll = (event: any) ...

What is the process for establishing a reference to a property of an object in JavaScript?

Imagine you have an object structured like this: obj = {a:{aa:1}, b:2}; You decide to create a convenient variable (referred to as a pointer) named x that points to obj.a.aa with the following code: x = obj.a.aa; Next, your goal is to update the value ...