guest
guest

Reputation: 2234

create form dynamically and submit it

So I have a jQuery plugin I wrote below, in plugin.js. I want to be able to also submit the form via JSON/AJAX every time it's created.

(function ( $ ) {
    $.fn.create = function() {
        var form = '<div id="form" class="container">';
        form += '<div>User Login</div>';
        form += '<form action="/create/one" method="post">';
        form += '<input type="text" name="name" placeholder="name">';
        form += '<input type="email" name="email" placeholder="email">';
        form += '<button type="submit">Login</button>';
        form += '</form>';
        form += '</div>';
        $('#form').submit(function(e)
        {

            var postData = form.find('form').serializeArray();
        if(postData.name === "someREGEXstring" || postData.email === "someREGEXstring") {
        console.log("empty inputs not cool");   
        }
    var formURL = $('form').attr("action");
    $.ajax(
    {
        url : formURL,
        type: "POST",
        data : postData,
        success:function(data, textStatus, jqXHR) 
        {

        },
        error: function(jqXHR, textStatus, errorThrown) 
        {
        }
    });
    e.preventDefault(); //STOP default action
});

$('#form').submit(); //SUBMIT FORM

        return this.append(form);
    };
}( jQuery ));

in HTML view

<div id="newForm"></div>

<script>
$(document).ready(function(){
    $("#newForm").create(); 
});
</script>

Is this the correct way to make this or should I:

  1. Create a another namespace under the same file for the AJAX portion
  2. Create another namespace under a different file the AJAX portion

Upvotes: 1

Views: 849

Answers (4)

Ashish Kumar
Ashish Kumar

Reputation: 3039

I have some chages, like:

  • $('#form').submit(function(e) should be $(form).submit(function(e) as variable form contains all the HTML of form wrapped within DIV.
  • in the submit of form, $(this) will refer to the form element itself.

Here is the modified code:

(function ($) {
    $.fn.create = function () {
        var formContainer = $("<div />", {
            id : "form",
            class : "container"
        }).append("<div>User Login</div>");

        var form = $("<form />", {
            action: "/create/one",
            method : "post",
            submit : function(e){
                var actionUrl = $(this).attr("action");

                alert(actionUrl); // just to check if this is working or not

                $.ajax({
                    url : actionUrl,
                    type : "POST",
                    data : $(this).serializeArray(),
                    success : function (data, textStatus, jqXHR) {},
                    error : function (jqXHR, textStatus, errorThrown) {}
                });
                e.preventDefault();
            }
        })
            .append('<input type="text" name="name" placeholder="name"><input type="email" name="email" placeholder="email"><button type="submit">Login</button>')
            .appendTo(formContainer);

        return this.append(formContainer);
    };
}(jQuery));

$("#test").create();

HTML for testing:

<div id="test"></div>

JS fiddle: http://jsfiddle.net/ashishanexpert/y99mt/2/

I have created the HTML nodes via jquery instead of just HTML string. attaching events to nodes is easier than converting string to HTML first and then attaching event to them. Hope you like it.

Upvotes: 0

iCollect.it Ltd
iCollect.it Ltd

Reputation: 93631

If the question is purely about how to arrange the code, I would suggest you pull the form template out of the code completely and make your plugin more flexible.

  • Option 1. Create the form as a template in the page and pass the template selector to plugin as an option
  • Option 2: Pass the template to your plugin

Here is an example of the first technique: http://jsfiddle.net/TrueBlueAussie/c8bmw/7/

Template in HTML:

<script id="template" type="template">
    <div id="form" class="container">
        <div>User Login</div>
        <form action="/create/one" method="post"/>
            <input type="text" name="name" placeholder="name"/>
            <input type="email" name="email" placeholder="email"/>
            <button type="submit">Login</button>
        </form>
    </div>
</script>

Create with:

$(document.body).create('#template');

And plugin simplified to:

(function ( $ ) {
    $.fn.create = function(template) {
        form = $($(template).text());
        form.submit(function(e) {
            // This is the actual form object now
            var $form = $(this).find('form');
            // Test contents of form here

            // If values are correct proceed with Ajax call
            var postData = $form.serializeArray();
            var formURL = $form.attr("action");
            $.ajax(
            {
                url : formURL,
                type: "POST",
                data : postData,
                success:function(data, textStatus, jqXHR) 
                {

                },
                error: function(jqXHR, textStatus, errorThrown) 
                {
                }
            });
            e.preventDefault(); // Stop default action
        });
        return this.append(form);
    };
}( jQuery ));

Now your plugin code will work with any form.

Based on your comment I have removed the automatic submit of the form, as that made no sense

Upvotes: 1

Minko Gechev
Minko Gechev

Reputation: 25682

This should work:

(function ( $ ) {
    $.fn.create = function() {
        var form = '<div id="form" class="container">';
        form += '<div>User Login</div>';
        form += '<form action="/create/one" method="post">';
        form += '<input type="text" name="name" placeholder="name">';
        form += '<input type="email" name="email" placeholder="email">';
        form += '<button type="submit">Login</button>';
        form += '</form>';
        form += '</div>';
        form = $(form);
        form.submit(function(e) {
            var postData = form.find('form').serializeArray();
            var formURL = form.find('form').attr("action");
            $.ajax(
            {
                url : formURL,
                type: "POST",
                data : postData,
                success:function(data, textStatus, jqXHR) 
                {

                },
                error: function(jqXHR, textStatus, errorThrown) 
                {
                }
            });
            e.preventDefault(); //STOP default action
        });
        form.submit(); //SUBMIT FORM

        return this.append(form);
    };
}( jQuery ));

Here is a demo in JSFiddle.

What is fixed:

  1. form = $(form) is used in order to create the DOM elements based on the form string.
  2. Change the way postData, formURL are initialized.

Upvotes: 1

Aditya
Aditya

Reputation: 107

<div id="#newForm"></div>

should be

<div id="newForm"></div>

to load this form element

Upvotes: 0

Related Questions