Tips on how to submit a form with appended information in a separate

There is a button labeled NEWFORM to create a new form when clicked. Every form includes a submit button. After clicking the submit button of each form, the values within that particular form are sent via AJAX. The issue arises when a new form is created and submitted, causing all form values to be sent together.

Below is the snippet of code:

$(document).ready(function() {
  $(".newform").click(function() {
    $(".MyForm")
    .eq(0)
    .clone()
    .show()
    .insertAfter(".MyForm:last");
  });

  $(document).on('click', '.MyForm button[type=submit]', function(e) {
    e.preventDefault() // Ensures the form is not immediately submitted 
    $('.MyForm').each(function() {
     console.log($(this).serialize())
      $.ajax(
        $(this).attr('action'), 
        {
          method: $(this).attr('method'),
          data: $(this).serialize()
        }
      )
    });
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.1/jquery.min.js"></script>
<span class="newform">NEWFORM+</span>
<div class="all">
  <form class="MyForm" method="post">
    <input type="text" placeholder="name" value="Aynaz" name="a1" />
    <select name="Avg">
      <option value="1">1</option>
      <option value="2">2</option>
    </select>
    <button type="submit">Submit</button>
  </form>
</div>

Answer №1

To successfully submit all ".MyForm" objects in your solution, you must first iterate through each form and determine the correct one to submit when onClick event occurs:

$(document).ready(function() {
  $(".newform").click(function() {
    $(".MyForm")
    .eq(0)
    .clone()
    .show()
    .insertAfter(".MyForm:last");
  });

  $(document).on('click', '.MyForm button[type=submit]', function(e) {
    e.preventDefault() // Ensure form is not submitted 
    var $frm = $(this).closest('.MyForm');
    console.log($frm.serialize());
    $.ajax(
        $frm.attr('action'), 
        {
          method: $frm.attr('method'),
          data: $frm.serialize()
        }
    );
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.1/jquery.min.js"></script>
<span class="newform">NEWFORM+</span>
<div class="all">
  <form class="MyForm" method="post">
    <input type="text" placeholder="name" value="Aynaz" name="a1"/>
    <select name="Avg">
      <option value="1">1</option>
      <option value="2">2</option>
    </select>
    <button type="submit">Submit</button>
  </form>
</div>

Answer №2


$(document).ready(function() {
    $(".newform").on('click', function() {
        $(".MyForm")
            .eq(0)
            .clone()
            .show()
            .insertAfter(".MyForm:last");
    });

    $(document).on('click', '.MyForm button[type=submit]', function(e) {
        e.preventDefault(); // Prevent form submission
        var $this = $(this).closest("form");
        console.log($this.serialize());
        $.ajax({
            url: $(this).attr('action'),
            method: $this.attr('method'),
            data: $this.serialize()
        });
    });
});

Answer №3

Instead, you might consider trying this approach:

$(document ).on('submit', '.myForm', function(e) {
    e.preventDefault();
    $.ajax({
        type: 'post',
        data: $(this).serialize(),
        url: 'submit.php'
    });
});

The issue lies in how you are using $(this) within your context.

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

Most secure methods to safeguard videos from unauthorized downloading

How can I increase the security measures to prevent users from easily downloading videos from my website? While I understand that it is impossible to completely stop downloads, I am looking for ways to make it more challenging than just a simple right-cl ...

The TextBox will alter its color following an incorrect submission

I am struggling to create a bootstrap form that will change the color of the borders to red after incorrect submission. The issue I am facing is that the textbox always remains in red. Does anyone have any suggestions for setting the textbox borders to red ...

Prevent floating labels from reverting to their initial position

Issue with Form Labels I am currently in the process of creating a login form that utilizes labels as placeholders. The reason for this choice is because the labels will need to be translated and our JavaScript cannot target the placeholder text or our de ...

What is the best method to update the content of one div with content from another page using AJAX?

Having trouble achieving smoother page loads? My goal is to utilize AJAX to specifically fetch a certain div from another page and then swap out the content of a div on this current page with the response. Below is my JavaScript script that uses AJAX to r ...

Discover the process of loading one controller from another controller in Angular JS

Is it possible to load an entire controller1 from a different controller2, not just a function? ...

Encountering an error message stating, "Unable to assign value to 'onclick' property"

Currently, I am at a beginner level in Javascript. While working on some exercises, I encountered an issue with the 'onclick' function as mentioned above. Despite going through other queries in this forum, I have not found a solution that works ...

A beginner's guide to integrating $.post with Django

Is there a way to incorporate the CSRF token into the post data when using the jquery.post() method in Django? Here is an example of what I am trying to accomplish: var postdata={ 'username':$('#login-email').val(), &apo ...

I'm curious, what height would be most suitable for a first impression?

I'm in the process of building a website and I want to ensure that all elements are visible within the div without requiring users to scroll. However, I know that screen resolutions vary between computers. What can I do to address this issue? Is ther ...

"Troubleshooting issues with the functionality of AngularJS - Bootstrap Material Datetimepicker

I recently implemented a datetimepicker from this datetimepicker library into my AngularJS project. I have included jQuery, Moment, and the datetimepicker in the head tag. The input field is nested within an ng-repeat, and I have initialized the datetimepi ...

HTML input form - issue with combining multiple patterns

Below is a section of my HTML code: <input type="text" #version tabindex="1" class="form-control" id="version" name="version" placeholder="" [(ngModel)]="application.version" required minlength="1" pattern="\d{1 ...

javascript search for parent function argument

I am struggling to figure out how to locate the key in my json array. When I try to find the key using a function parameter, it does not seem to work. This is a snippet of my json data: ... { "product": [ { "title": " ...

drop down menu in navigation bar: unable to display items

I am having trouble with a dropdown menu in my code. Even though I used the code from the official Bootstrap website, the items are not appearing in the dropdown list. <nav class="navbar navbar-expand-lg navbar-dark bg-primary "> ...

Oops! The Route.post() function is looking for a callback function, but instead, it received an [object Object

Looking to integrate a password reset feature in my web app, but encountering the error mentioned in the title. Here's a snippet of my code: main.js: const router = express.Router(); const AsyncNewPassword = require('./controller/asyncnewpasswor ...

Implementing CSS animations in ReactJS: A guide to activating onClick and onHover events

Is there a way to activate the onClick and onHover CSS animations for the ReactJS button component below? I attempted to use ref = {input => (this.inputElement = input)}, but I only see the animation when clicking the button. <td> ...

How do you determine the length of an array of arrays using jQuery if it is 'undefined'?

Looking at the array structure below: mdarray = { '0001':{address:'add1',title:'title1'}, '0002':{address:'add2',title:'title2'}, '0003':{address:'add3',title:'titl ...

What does it mean in Javascript when b1 is undefined while o1 has a value and is equal to b1?

Having some issues getting variables to work with drop down options on a page. At first, I couldn't even extract a value from the function but managed to do so by removing "var" from o1. Strange thing is, when I type o1 into the js console on chrome i ...

Disabling the <A> tag within an image due to image map functionality

My thumbnails are set up to be different links, usually accomplished with this code: <a href=#><img src=# /></a> However, I have now converted each thumbnail into an image map (changing the thumbnail as you mouse over). Despite my attem ...

What steps should I take to create a JavaScript-based downloader application?

I am looking for a way to sell some files from my Web Server to clients. I have created my own HTTP server and I have experience programming in HTML, CSS, and a little bit of JavaScript. While I have seen tutorials on creating download links with HTML 5, I ...

Tips for smoothly adding new content to a jQuery AJAX autoupdating div

I'm currently working on a div that pulls data from an external PHP file, which loops through results from a MySQL query. My goal is to have this div update every 5 seconds using AJAX, with only the new results smoothly fading in at the top of the lis ...

Unable to save screenshot in the report portal while running with WebDriver.io (wdio) execution

In my webdriverio project, the directory structure is as follows: e2e/ utilities/pUtil.js report/screenshot specs wdio.config.js Within pUtil.js file, I have the following code snippet: static takeScreenshot(name, failure = false, test) { const path = ...