Dynamically create and submit form

There were two things wrong with your code. The first one is that you included the $(document).ready(); but didn’t wrap the jQuery object that’s creating the element with it.

The second was the method you were using. jQuery will create any element when the selector (or where you would usually put the selector) is replaced with the element you wish to create. Then you just append it to the body and submit it.

$(document).ready(function(){
    $('<form action="form2.html"></form>').appendTo('body').submit();
});

Here’s the code in action. In this example, it doesn’t auto submit, just to prove that it would add the form element.

Here’s the code with auto submit. It works out fine. Jsfiddle takes you to a 404 page because “form2.html” doesn’t exist on its server, obviously.

Leave a Comment