简体   繁体   English

动态创建表单并提交

[英]create form dynamically and submit it

So I have a jQuery plugin I wrote below, in plugin.js. 因此,我在plugin.js中有一个下面编写的jQuery插件。 I want to be able to also submit the form via JSON/AJAX every time it's created. 我希望每次创建表单时都可以通过JSON / AJAX提交表单。

(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 在HTML视图中

<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 在同一文件下为AJAX部分创建另一个名称空间
  2. Create another namespace under a different file the AJAX portion 在AJAX部分的不同文件下创建另一个名称空间

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 . 这是JSFiddle中的演示。

What is fixed: 固定的是:

  1. form = $(form) is used in order to create the DOM elements based on the form string. form = $(form)用于基于form字符串创建DOM元素。
  2. Change the way postData , formURL are initialized. 更改postDataformURL的初始化方式。

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 选项1.将表单创建为页面中的模板,并将模板选择器作为选项传递给插件
  • Option 2: Pass the template to your plugin 选项2:将模板传递给您的插件

Here is an example of the first technique: http://jsfiddle.net/TrueBlueAussie/c8bmw/7/ 这是第一种技术的示例: http : //jsfiddle.net/TrueBlueAussie/c8bmw/7/

Template in HTML: 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 根据您的评论,我删除了自动提交表单的步骤,因为这没有任何意义

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

should be 应该

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

to load this form element 加载此表单元素

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. $('#form').submit(function(e)应该为$(form).submit(function(e)因为变量form包含包装在DIV中的所有HTML表单。
  • in the submit of form, $(this) will refer to the form element itself. 在表单提交中, $(this)将引用表单元素本身。

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: 用于测试的HTML:

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

JS fiddle: http://jsfiddle.net/ashishanexpert/y99mt/2/ JS小提琴: http //jsfiddle.net/ashishanexpert/y99mt/2/

I have created the HTML nodes via jquery instead of just HTML string. 我已经通过jquery创建了HTML节点,而不仅仅是HTML字符串。 attaching events to nodes is easier than converting string to HTML first and then attaching event to them. 将事件附加到节点比先将字符串转换为HTML然后再将事件附加到节点要容易。 Hope you like it. 希望你喜欢。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM