使用jquery动态创建表单并提交

时间:2022-11-07 13:26:01

I am trying to create a form dynamically via jquery and submit it to a PHP file. This creates the form but nothing happens when i click the submit button. What is going wrong here ?

我试图通过jquery动态创建一个表单并将其提交到PHP文件。这会创建表单但单击提交按钮时没有任何反应。这里出了什么问题?

Method i am using to create a form dynamically is :-

我用来动态创建表单的方法是: -

    $('#share').append("<form action='sharer.php' method='POST'/>");
    $('#share').append("<div class= 'appm'>Save this/div/>");
    $('#share').append("<input type='text' placeholder='Name' name='routename' id='rname'/>");
    $('#share').append("<input type='text' placeholder='description' id='rdescription' name='routedescription' class= 'address'/>");
    $('#share').append("<input type='text' placeholder='tags' id='tags' name='routetags'  />");
    $('#share').append("<br><input type='submit' id='savebutton' value = 'Save' />");
    $('#share').append("</form>");

5 个解决方案

#1


20  

Solution

You are appending all the content that you add to the parent element, so they won't get inside the form itself. Way to fix this:

您要将添加到父元素的所有内容附加到其中,因此它们不会进入表单本身。解决这个问题的方法:

   $("#share").append('<form action="sharer.php" method="POST">');
   $("#share form").append('<div class="appm">Save this</div>');
   $("#share form").append('<input type="text" placeholder="Name" name="routename" id="rname"/>');
   $("#share form").append('<input type="text" placeholder="description" id="rdescription" name="routedescription" class="address"/>');
   $("#share form").append('<input type="text" placeholder="tags" id="tags" name="routetags"/>');
   $("#share form").append('<br><input type="submit" id="savebutton" value="Save" />');

You don't need to append a closing tag for the form after that.

之后您不需要为表单附加结束标记。

Working Fiddle


Performance-wise: Pure JavaScript

(jsperf link up there)

(jsperf链接那里)

If you really want a good performance solution, go for pure JavaScript code:

如果您真的想要一个好的性能解决方案,请选择纯JavaScript代码:

var div = document.getElementById('share');
var form = document.createElement('form');
form.setAttribute('action', 'sharer.php');
form.setAttribute('method', 'POST');
/*-----------*/
var appm = document.createElement('div');
appm.appendChild(document.createTextNode('Save This'));
appm.setAttribute('class', 'appm');
/*-----------*/

var input1 = document.createElement('input');
input1.setAttribute('type', 'text');
input1.setAttribute('placeholder', 'Name');
input1.setAttribute('name', 'routename');
input1.setAttribute('id', 'rname');

var input2 = document.createElement('input');
input2.setAttribute('type', 'text');
input2.setAttribute('placeholder', 'description');
input2.setAttribute('name', 'routedescription');
input2.setAttribute('id', 'rdescription');
input2.setAttribute('class', 'address');

var tags = document.createElement('input');
tags.setAttribute('type', 'text');
tags.setAttribute('placeholder', 'tags');
tags.setAttribute('name', 'routetags');
tags.setAttribute('id', 'tags');

var submit = document.createElement('input');
submit.setAttribute('type', 'submit');
submit.setAttribute("value", "Save");
submit.setAttribute('id', 'savebutton');

form.appendChild(input1);
form.appendChild(input2);
form.appendChild(tags);
form.appendChild(submit);

div.appendChild(form);

#2


14  

First of all, There is way easier way to write that. Second, you're not appending anything to the form. I would rewrite that one of 2 ways.

首先,有更简单的方法来编写它。其次,你没有在表格中添加任何内容。我会改写两种方式中的一种。

Example 1

<script type="text/javascript">
    $(function() {
        $('#share').append(
            $('<form />', { action: 'sharer.php', method: 'POST' }).append(
                $('<div />', { class: 'appm', text: 'Save this' }),
                $('<input />', { id: 'rname', name: 'routename', placeholder: 'Name', type: 'text' }),
                $('<input />', { class: 'address', id: 'rdescription', name: 'routedescription', placeholder: 'description', type: 'text' }),
                $('<input />', { id: 'tags', name: 'routetags', placeholder: 'tags', type: 'text' }),
                $('<br />'),
                $('<input />', { id: 'savebutton', type: 'submit', value: 'Save' })
            )
        )
    })
</script>

With Example 1, you may need to asign events dynamically. Such as:

使用示例1,您可能需要动态地设置事件。如:

<script type="text/javascript">
    $(function() {
        $(document).on('click', '#share form input[type=submit]', function(e) {
            e.preventDefault();
            /*  do work */
        })
    })
</script>

Example 2

<script type="text/javascript">
    $(function() {
        var $form = $('<form />', { action: 'sharer.php', method: 'POST' }),
            frmSave = $('<div />', { class: 'appm', text: 'Save this' }),
            frmRName = $('<input />', { id: 'rname', name: 'routename', placeholder: 'Name', type: 'text' }),
            frmRDesc = $('<input />', { class: 'address', id: 'rdescription', name: 'routedescription', placeholder: 'description', type: 'text' }),
            frmRTags = $('<input />', { id: 'tags', name: 'routetags', placeholder: 'tags', type: 'text' }),
            frmButton = $('<input />', { id: 'savebutton', type: 'submit', value: 'Save' });

        $form.append(frmSave, frmRName, frmRDesc, frmRTags, $('<br />'), frmButton).appendTo($('#share'));
    })
</script>

With example 2, you can make later use of the variables (even make them global if needed) and make changes using variables, such as:

使用示例2,您可以稍后使用变量(如果需要,甚至将它们设置为全局变量)并使用变量进行更改,例如:

<script type="text/javascript">
    $(function() {
        frmButton.on('click', function(e) {
            e.preventDefault();
            /*  do work */
        })
    })
</script>

#3


4  

JQuery will never allow you to put a tag without closing it. So now, your code create a form and appen elements after the form (not inside).

JQuery永远不会允许你在不关闭标记的情况下放置标记。所以现在,你的代码在表单之后创建一个表单和appen元素(不在里面)。

But you can create a form, save it in a var and append your things into the var.

但是你可以创建一个表单,将其保存在var中并将你的东西附加到var中。

var form = $('<form/>', {action : 'sharer.php', method : 'POST'}).appendTo('#share');
form.append("<div class= 'appm'>Save this</div>");
form.append("<input type='text' placeholder='Name' name='routename' id='rname'/>");
form.append("<input type='text' placeholder='description' id='rdescription' name='routedescription' class= 'address'/>");
form.append("<input type='text' placeholder='tags' id='tags' name='routetags'  />");
form.append("<br/><input type='submit' id='savebutton' value='Save' />");

This is also optimal since you are caching the form, not creating a jQuery object for each append!

这也是最佳的,因为你正在缓存表单,而不是为每个追加创建一个jQuery对象!

Working fiddle : http://jsfiddle.net/Lb8BY/ (append to body)

工作小提琴:http://jsfiddle.net/Lb8BY/(附加到正文)

#4


1  

@Karl-André Gagnon - think outside the box :)

@ Karl-AndréGagnon - 在盒子外面思考:)

        //Start
        var $positionTitle = $('.fac_ad_apply_title').text(),
            $departmentTitle = $('.fac_ad_apply_appt_org').text();
            $requiredText = $('.fac_ad_apply_required').text();

        //Creating variables - contact information
        var $form = $('#user_response'),
            $formAttr = $form.attr(),
            $firstName = $('#first_name').attr(),
            $middleName = $('#middle_name').attr(),
            $lastName = $('#last_name').attr(),
            $suffixName = $('#suffix').attr(),
            $email = $('#email').attr()

    //Form
        $('#fac_ad').before(
            $('<h1 />').append($positionTitle),
            $('<h3 />').append($departmentTitle),
            $('<p />').append($requiredText),
            $('<form />', $formAttr).append(

                //Contact Information
                $('<div class="form-group" />').append(
                    $('<label for="">First Name</label>'),
                    $('<input class="form-control" />', $firstName)
                ),
                $('<div class="form-group" />').append(
                    $('<label for="">Middle Name</label>'),
                    $('<input class="form-control" />', $middleName)
                ),
                $('<div class="form-group" />').append(
                    $('<label for="">Last Name</label>'),
                    $('<input class="form-control" />', $lastName)
                ),
                $('<div class="form-group" />').append(
                    $('<label for="">Email address</label>'),
                    $('<input class="form-control" />', $suffixName)
                ),
                $('<div class="form-group" />').append(
                    $('<label for="">Suffix/Degree(s)</label>'),
                    $('<input class="form-control" />', $email)
                )
            )
        )

#5


0  

I would submit the form using the jQuery on() method, it allows you to bind events to dynamically created elements anchored by static elements such as the body tag

我将使用jQuery on()方法提交表单,它允许您将事件绑定到由静态元素(如body标签)锚定的动态创建的元素

$("body").on("submit", "#share form", function(event){
    event.preventDefault();
});

In your case, if the form isn't submitting I would use ajax to submit the form instead of the standard form submit. You could even execute a javascript page refresh after its done if you want a refresh to happen

在您的情况下,如果表单未提交,我将使用ajax提交表单而不是标准表单提交。如果要进行刷新,您甚至可以在完成后执行javascript页面刷新

$("body").on("submit", "#share form", function(event){
    event.preventDefault();
    // Grab all form data
    var formInputData = $(this).serializeObject();
    // send form data to php file in $_POST array
    $.post("sharer.php", formInputData, function(data){
        // log errors or anything that is echoed back from php file
        console.log(data);
        // refresh the page
        window.location.reload();
    });
});

Don't forget to put it all in a document ready function and have the jQuery library included in your HTML head tag

不要忘记将它全部放在文档就绪函数中,并在HTML头标记中包含jQuery库

$(document).ready(function(){
    $("body").on("submit", "#share form", function(event){
        event.preventDefault();
        // Grab all form data
        var formInputData = $(this).serializeObject();
        // send form data to php file in $_POST array
        $.post("sharer.php", formInputData, function(data){
            // log errors or anything that is echoed back from php file
            console.log(data);
            // refresh the page
            window.location.reload();
        });
    });
});

jQuery include example

jQuery包含示例

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>

#1


20  

Solution

You are appending all the content that you add to the parent element, so they won't get inside the form itself. Way to fix this:

您要将添加到父元素的所有内容附加到其中,因此它们不会进入表单本身。解决这个问题的方法:

   $("#share").append('<form action="sharer.php" method="POST">');
   $("#share form").append('<div class="appm">Save this</div>');
   $("#share form").append('<input type="text" placeholder="Name" name="routename" id="rname"/>');
   $("#share form").append('<input type="text" placeholder="description" id="rdescription" name="routedescription" class="address"/>');
   $("#share form").append('<input type="text" placeholder="tags" id="tags" name="routetags"/>');
   $("#share form").append('<br><input type="submit" id="savebutton" value="Save" />');

You don't need to append a closing tag for the form after that.

之后您不需要为表单附加结束标记。

Working Fiddle


Performance-wise: Pure JavaScript

(jsperf link up there)

(jsperf链接那里)

If you really want a good performance solution, go for pure JavaScript code:

如果您真的想要一个好的性能解决方案,请选择纯JavaScript代码:

var div = document.getElementById('share');
var form = document.createElement('form');
form.setAttribute('action', 'sharer.php');
form.setAttribute('method', 'POST');
/*-----------*/
var appm = document.createElement('div');
appm.appendChild(document.createTextNode('Save This'));
appm.setAttribute('class', 'appm');
/*-----------*/

var input1 = document.createElement('input');
input1.setAttribute('type', 'text');
input1.setAttribute('placeholder', 'Name');
input1.setAttribute('name', 'routename');
input1.setAttribute('id', 'rname');

var input2 = document.createElement('input');
input2.setAttribute('type', 'text');
input2.setAttribute('placeholder', 'description');
input2.setAttribute('name', 'routedescription');
input2.setAttribute('id', 'rdescription');
input2.setAttribute('class', 'address');

var tags = document.createElement('input');
tags.setAttribute('type', 'text');
tags.setAttribute('placeholder', 'tags');
tags.setAttribute('name', 'routetags');
tags.setAttribute('id', 'tags');

var submit = document.createElement('input');
submit.setAttribute('type', 'submit');
submit.setAttribute("value", "Save");
submit.setAttribute('id', 'savebutton');

form.appendChild(input1);
form.appendChild(input2);
form.appendChild(tags);
form.appendChild(submit);

div.appendChild(form);

#2


14  

First of all, There is way easier way to write that. Second, you're not appending anything to the form. I would rewrite that one of 2 ways.

首先,有更简单的方法来编写它。其次,你没有在表格中添加任何内容。我会改写两种方式中的一种。

Example 1

<script type="text/javascript">
    $(function() {
        $('#share').append(
            $('<form />', { action: 'sharer.php', method: 'POST' }).append(
                $('<div />', { class: 'appm', text: 'Save this' }),
                $('<input />', { id: 'rname', name: 'routename', placeholder: 'Name', type: 'text' }),
                $('<input />', { class: 'address', id: 'rdescription', name: 'routedescription', placeholder: 'description', type: 'text' }),
                $('<input />', { id: 'tags', name: 'routetags', placeholder: 'tags', type: 'text' }),
                $('<br />'),
                $('<input />', { id: 'savebutton', type: 'submit', value: 'Save' })
            )
        )
    })
</script>

With Example 1, you may need to asign events dynamically. Such as:

使用示例1,您可能需要动态地设置事件。如:

<script type="text/javascript">
    $(function() {
        $(document).on('click', '#share form input[type=submit]', function(e) {
            e.preventDefault();
            /*  do work */
        })
    })
</script>

Example 2

<script type="text/javascript">
    $(function() {
        var $form = $('<form />', { action: 'sharer.php', method: 'POST' }),
            frmSave = $('<div />', { class: 'appm', text: 'Save this' }),
            frmRName = $('<input />', { id: 'rname', name: 'routename', placeholder: 'Name', type: 'text' }),
            frmRDesc = $('<input />', { class: 'address', id: 'rdescription', name: 'routedescription', placeholder: 'description', type: 'text' }),
            frmRTags = $('<input />', { id: 'tags', name: 'routetags', placeholder: 'tags', type: 'text' }),
            frmButton = $('<input />', { id: 'savebutton', type: 'submit', value: 'Save' });

        $form.append(frmSave, frmRName, frmRDesc, frmRTags, $('<br />'), frmButton).appendTo($('#share'));
    })
</script>

With example 2, you can make later use of the variables (even make them global if needed) and make changes using variables, such as:

使用示例2,您可以稍后使用变量(如果需要,甚至将它们设置为全局变量)并使用变量进行更改,例如:

<script type="text/javascript">
    $(function() {
        frmButton.on('click', function(e) {
            e.preventDefault();
            /*  do work */
        })
    })
</script>

#3


4  

JQuery will never allow you to put a tag without closing it. So now, your code create a form and appen elements after the form (not inside).

JQuery永远不会允许你在不关闭标记的情况下放置标记。所以现在,你的代码在表单之后创建一个表单和appen元素(不在里面)。

But you can create a form, save it in a var and append your things into the var.

但是你可以创建一个表单,将其保存在var中并将你的东西附加到var中。

var form = $('<form/>', {action : 'sharer.php', method : 'POST'}).appendTo('#share');
form.append("<div class= 'appm'>Save this</div>");
form.append("<input type='text' placeholder='Name' name='routename' id='rname'/>");
form.append("<input type='text' placeholder='description' id='rdescription' name='routedescription' class= 'address'/>");
form.append("<input type='text' placeholder='tags' id='tags' name='routetags'  />");
form.append("<br/><input type='submit' id='savebutton' value='Save' />");

This is also optimal since you are caching the form, not creating a jQuery object for each append!

这也是最佳的,因为你正在缓存表单,而不是为每个追加创建一个jQuery对象!

Working fiddle : http://jsfiddle.net/Lb8BY/ (append to body)

工作小提琴:http://jsfiddle.net/Lb8BY/(附加到正文)

#4


1  

@Karl-André Gagnon - think outside the box :)

@ Karl-AndréGagnon - 在盒子外面思考:)

        //Start
        var $positionTitle = $('.fac_ad_apply_title').text(),
            $departmentTitle = $('.fac_ad_apply_appt_org').text();
            $requiredText = $('.fac_ad_apply_required').text();

        //Creating variables - contact information
        var $form = $('#user_response'),
            $formAttr = $form.attr(),
            $firstName = $('#first_name').attr(),
            $middleName = $('#middle_name').attr(),
            $lastName = $('#last_name').attr(),
            $suffixName = $('#suffix').attr(),
            $email = $('#email').attr()

    //Form
        $('#fac_ad').before(
            $('<h1 />').append($positionTitle),
            $('<h3 />').append($departmentTitle),
            $('<p />').append($requiredText),
            $('<form />', $formAttr).append(

                //Contact Information
                $('<div class="form-group" />').append(
                    $('<label for="">First Name</label>'),
                    $('<input class="form-control" />', $firstName)
                ),
                $('<div class="form-group" />').append(
                    $('<label for="">Middle Name</label>'),
                    $('<input class="form-control" />', $middleName)
                ),
                $('<div class="form-group" />').append(
                    $('<label for="">Last Name</label>'),
                    $('<input class="form-control" />', $lastName)
                ),
                $('<div class="form-group" />').append(
                    $('<label for="">Email address</label>'),
                    $('<input class="form-control" />', $suffixName)
                ),
                $('<div class="form-group" />').append(
                    $('<label for="">Suffix/Degree(s)</label>'),
                    $('<input class="form-control" />', $email)
                )
            )
        )

#5


0  

I would submit the form using the jQuery on() method, it allows you to bind events to dynamically created elements anchored by static elements such as the body tag

我将使用jQuery on()方法提交表单,它允许您将事件绑定到由静态元素(如body标签)锚定的动态创建的元素

$("body").on("submit", "#share form", function(event){
    event.preventDefault();
});

In your case, if the form isn't submitting I would use ajax to submit the form instead of the standard form submit. You could even execute a javascript page refresh after its done if you want a refresh to happen

在您的情况下,如果表单未提交,我将使用ajax提交表单而不是标准表单提交。如果要进行刷新,您甚至可以在完成后执行javascript页面刷新

$("body").on("submit", "#share form", function(event){
    event.preventDefault();
    // Grab all form data
    var formInputData = $(this).serializeObject();
    // send form data to php file in $_POST array
    $.post("sharer.php", formInputData, function(data){
        // log errors or anything that is echoed back from php file
        console.log(data);
        // refresh the page
        window.location.reload();
    });
});

Don't forget to put it all in a document ready function and have the jQuery library included in your HTML head tag

不要忘记将它全部放在文档就绪函数中,并在HTML头标记中包含jQuery库

$(document).ready(function(){
    $("body").on("submit", "#share form", function(event){
        event.preventDefault();
        // Grab all form data
        var formInputData = $(this).serializeObject();
        // send form data to php file in $_POST array
        $.post("sharer.php", formInputData, function(data){
            // log errors or anything that is echoed back from php file
            console.log(data);
            // refresh the page
            window.location.reload();
        });
    });
});

jQuery include example

jQuery包含示例

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>