Skip to content Skip to sidebar Skip to footer

Replace Html Form On Submit With Jquery

So here's what I'm trying to do: in my webpage, I have a lot of HTML forms. If any individual form is submitted, I want the entire form to be replaced with something. However, I ha

Solution 1:

The code looks about right, assuming $("#commentreply").each(function() is temporary and you're going to select more than one form instead.

But currently the form is posting because

$(this).submit(function() {
    event.preventDefault();

you're not preventing anything.

$(this).submit(function(event) { // <-- You need to declare event
    event.preventDefault();

To answer your second question, if you can use each, use each rather than duplicate code.

Also, if there are many forms, you shouldn't bind the event until the user uses the form saves, slowing down your page.

Re the error Uncaught TypeError: Cannot call method "createDocumentFragment"

Without checking, this might be because of this:

posting.done(function(data) {
    $(this).replaceWith("(HTML content to replace form)");
}).error(function(){

$(this) is now posting, not the form.

Insert after this line

$("#commentreply").each(function() {
    var $form = $(this);

and replace

$(this).replaceWith("(HTML content to replace form)");

with

$form.replaceWith("<div>(HTML content to replace form)</div>");

making it an HTML element not just a string.

Solution 2:

I would use another approach:

When submit triggers → replace the parent form:

$('form').submit(function(event){

    event.preventDefault();
    /* Fire your validation and $.post */

    $(this).replaceWith("<div>new HTML content to replace with</div>");
});

And you can even animate it:

$('form').submit(function(event){

    event.preventDefault();
    /* Fire your validation and $.post */

    $(this).slideUp(function(){
        $(this).replaceWith(
            $("<div style='display:none'>new HTML content to replace with</div>").slideDown()
        );
    });
});

It is not tested.

Post a Comment for "Replace Html Form On Submit With Jquery"