Javascript jQuery - 动态创建隐藏的表单元素
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2408043/
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
jQuery - Create hidden form element on the fly
提问by Mithun Sreedharan
What is the simplest way to dynamically create a hidden inputform field using jQuery?
使用 jQuery动态创建隐藏输入表单字段的最简单方法是什么?
回答by David Hellsing
$('<input>').attr('type','hidden').appendTo('form');
To answer your second question:
回答你的第二个问题:
$('<input>').attr({
type: 'hidden',
id: 'foo',
name: 'bar'
}).appendTo('form');
回答by Mark Bell
$('#myformelement').append('<input type="hidden" name="myfieldname" value="myvalue" />');
回答by Sergey Onishchenko
The same as David's, but without attr()
与 David 的相同,但没有 attr()
$('<input>', {
type: 'hidden',
id: 'foo',
name: 'foo',
value: 'bar'
}).appendTo('form');
回答by Slipstream
if you want to add more attributes just do like:
如果您想添加更多属性,请执行以下操作:
$('<input>').attr('type','hidden').attr('name','foo[]').attr('value','bar').appendTo('form');
Or
或者
$('<input>').attr({
type: 'hidden',
id: 'foo',
name: 'foo[]',
value: 'bar'
}).appendTo('form');
回答by Saurabh Chandra Patel
function addHidden(theForm, key, value) {
// Create a hidden input element, and append it to the form:
var input = document.createElement('input');
input.type = 'hidden';
input.name = key;'name-as-seen-at-the-server';
input.value = value;
theForm.appendChild(input);
}
// Form reference:
var theForm = document.forms['detParameterForm'];
// Add data:
addHidden(theForm, 'key-one', 'value');
回答by Subodh Ghulaxe
Working JSFIDDLE
工作JSFIDDLE
If your form is like
如果你的表格是这样的
<form action="" method="get" id="hidden-element-test">
First name: <input type="text" name="fname"><br>
Last name: <input type="text" name="lname"><br>
<input type="submit" value="Submit">
</form>
<br><br>
<button id="add-input">Add hidden input</button>
<button id="add-textarea">Add hidden textarea</button>
You can add hidden input and textarea to form like this
您可以像这样添加隐藏的输入和文本区域来形成
$(document).ready(function(){
$("#add-input").on('click', function(){
$('#hidden-element-test').prepend('<input type="hidden" name="ipaddress" value="192.168.1.201" />');
alert('Hideen Input Added.');
});
$("#add-textarea").on('click', function(){
$('#hidden-element-test').prepend('<textarea name="instructions" style="display:none;">this is a test textarea</textarea>');
alert('Hideen Textarea Added.');
});
});
Check working jsfiddlehere
在此处检查工作jsfiddle

