aceslowman
aceslowman

Reputation: 631

Can't get jQuery submit() to work on form created by jQuery

So I have a tag system, and onclick, the tag button is changed into a form with one input and submit button. The problem is apparently with the fact that the form is being created AFTER the fact.

HTML:

<button class="btn btn-success addTag">
    <a href="">+</a>
    <span class="label addTagBody">Add a skill</span>
</button>

jQuery:

$('.addTag').click(function() {
    $('.addTag').replaceWith('<div class="btn btn-success addTag"><form name="addTag"><input placeholder="Enter new tag" type="text" class="addTagBody"><input type="submit" value="Add"></form></div>');
});

$("form[name='addTag']").on('submit', function(event) {
    event.preventDefault();
    alert($(this).serialize());
});

Any tips on handling scenarios like this?

Upvotes: 2

Views: 119

Answers (4)

Ragnar
Ragnar

Reputation: 4578

You have to bind on(submit) event after addTag because initially the form doesn't exists.

$('.addTag').click(function() {
    $('.addTag').replaceWith('<div class="btn btn-success addTag"><form name="addTag"><input placeholder="Enter new tag" type="text" class="addTagBody" name="tag"><input type="submit" value="Add"></form></div>');
    $("form[name='addTag']").on('submit', function(event) {
      event.preventDefault();
      alert($(this).serialize());
    });
});

Upvotes: 1

Igor
Igor

Reputation: 15893

You have to use existing element to bind an event for elements created in the future:

$(document).on("submit", "form[name='addTag']", function(){ ... });

Also, add name attribute to you form's text inputs for their values to be included in serialized form.

Upvotes: 1

jme11
jme11

Reputation: 17397

You'll need to use event delegation when you dynamically create elements. For more information read: http://learn.jquery.com/events/event-delegation/

$(document).on('submit', 'form[name="addTag"]', function(){ ... });

Upvotes: 1

Andre
Andre

Reputation: 190

change your jquery part to

$('.addTag').click(function() {
    $('.addTag').replaceWith('<div class="btn btn-success addTag"><form name="addTag"><input placeholder="Enter new tag" type="text" class="addTagBody"><input type="submit" value="Add"></form></div>');
    $("form[name='addTag']").on('submit', function(event) {
        event.preventDefault();
        alert($(this).serialize());
    });
});

so the form submition function is added every time the new form is created

Upvotes: 2

Related Questions