jQuery 使用jquery动态创建表单并提交
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17431760/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Create a form dynamically with jquery and submit
提问by user1263375
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>");
回答by Jeff Noel
Solution
解决方案
You are appending all the contentthat you add to the parent element, so they won't get inside the formitself. 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
性能方面:纯 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);
回答by SpYk3HH
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
示例 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,您可能需要events
动态分配。如:
<script type="text/javascript">
$(function() {
$(document).on('click', '#share form input[type=submit]', function(e) {
e.preventDefault();
/* do work */
})
})
</script>
Example 2
示例 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>
回答by Karl-André Gagnon
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 永远不会允许您在不关闭标签的情况下放置标签。所以现在,您的代码创建一个表单并在表单之后添加元素(不在内部)。
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/(附加到正文)
回答by Davis
@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)
)
)
)
回答by kiko carisse
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
我将使用 jQueryon()
方法提交表单,它允许您将事件绑定到由静态元素(例如 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
不要忘记将其全部放入文档就绪函数中,并将 jQuery 库包含在您的 HTML head 标记中
$(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>