本文翻译自:jQuery - Create hidden form element on the fly
使用jQuery动态创建隐藏输入表单字段的最简单方法是什么?
#1楼
参考:https://stackoom.com/question/A6RP/jQuery-动态创建隐藏的表单元素
#2楼
$('#myformelement').append('<input type="hidden" name="myfieldname" value="myvalue" />');
#3楼
$('<input>').attr('type','hidden').appendTo('form');
To answer your second question: 回答你的第二个问题:
$('<input>').attr({
type: 'hidden',
id: 'foo',
name: 'bar'
}).appendTo('form');
#4楼
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');
#5楼
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 您可以添加隐藏的输入和textarea来形成这样的形式
$(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 jsfiddle here 在这里检查工作jsfiddle
#6楼
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');