简体   繁体   中英

Create a form dynamically with jquery and submit

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 ?

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>");

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)

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

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);

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:

<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:

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

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).

But you can create a form, save it in a var and append your things into the 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!

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

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

        //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)
                )
            )
        )

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

$("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

$("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

$(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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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