roob
roob

Reputation: 2549

HTML Form created in javascript does not respond to .submit

I have added a form to my html page dynamically using javascript. The .submit on the form does not work when I do this. However if I create the exact same form in html, it works as expected.

Here is a fiddle: http://jsfiddle.net/dwha77g4/4/

The following code:

$('.submit-form').submit(function(e){
    alert("test");
    e.preventDefault();
});

runs on the first button in the fiddle, but not the second dynamically created one.

Upvotes: 0

Views: 265

Answers (4)

IgorAlves
IgorAlves

Reputation: 5556

For new objects in the DOM we must to use "on" jQuery function. http://api.jquery.com/on/ So try to change body for document as suggest rformal.

$(document).on("submit", ".submit_form", function(e){
    e.preventDefault();  
    alert("test");

});

Said that, you should not use "e.preventDefault" if you want to send your form. I dont know if it is your case, because e.preventDefault() will prevent the default event from occuring. See this post if you want to know better about that. event.preventDefault() vs. return false

Note: use submit_form instead submit-form

Upvotes: 1

The problem with your code is that when you add the listerner to the submit event, there is no element that matches with the query '.submit-form', because your dinamic form was not created yet.

You can do

$(document).ready(function() {
    var formHTML = "<li><form action='#' method='POST' class='submit-form'><input type='submit' value='submit dynamic' /></form></li>"
    $("#list-container").append(formHTML);

    $('.submit-form').submit(function(e){
       alert("test");
       e.preventDefault();
    });
});

Like that, you will create the form and then add the listener to the submit event.

Upvotes: 2

rfornal
rfornal

Reputation: 5122

Try ... Working Demo

$("body").on('submit', '.submit-form', function(e) {
  alert("test");
  e.preventDefault();
});

Basically, dynamically created content does not handle prior attached events well. Since the object did not exist when you attempted to run the submit, there was nothing to attach to. What I did here was attach an on event onto the body that searches for .submit-form, irregardless of when it was created.

Upvotes: 5

Born2Code
Born2Code

Reputation: 1075

The top code to create the event listener function runs before the html snippet is inserted to the DOM, so it is not tied to the actual form. You want to use the .on() to tie events to future added DOM content. Just checkout the jquery docs for .on(), pretty self explanatory.

you can also re-organize your code, so that the .submit() is set up after you insert the HTML snippet and should also work for you.

Upvotes: 1

Related Questions