如何在JavaScript中将隐藏字段创建为特定表单?
<html>
<head>
<script type="text/javascript">
var a =10;
function test() {
if (a ==10) {
// ... Here i need to create some hidden field for form named = chells
}
}
</script>
</head>
<body >
<form id="chells" name="formsdsd">
<INPUT TYPE=BUTTON OnClick="test();">
</form>
</body>
</html>
答案 0 :(得分:101)
var input = document.createElement("input");
input.setAttribute("type", "hidden");
input.setAttribute("name", "name_you_want");
input.setAttribute("value", "value_you_want");
//append to form element that you want .
document.getElementById("chells").appendChild(input);
答案 1 :(得分:20)
您可以使用jquery动态创建元素
$('#form').append('<input type="hidden" name="fieldname" value="fieldvalue" />');
或其他方式
$('<input>').attr({
type: 'hidden',
id: 'fieldId',
name: 'fieldname'
}).appendTo('form')
答案 2 :(得分:4)
我发现这个有用:
var element1 = document.createElement("input");
element1.type = "hidden";
element1.value = "10";
element1.name = "a";
document.getElementById("chells").appendChild(element1);
答案 3 :(得分:0)
您可以使用此方法创建带有/不带有表单的隐藏文本字段。如果您需要表单,则只需传递带有对象status = true
的表单。
您还可以添加多个隐藏字段。 使用这种方式:
CustomizePPT.setHiddenFields(
{
"hidden" :
{
'fieldinFORM' : 'thisdata201' ,
'fieldinFORM2' : 'this3' //multiple hidden fields
.
.
.
.
.
'nNoOfFields' : 'nthData'
},
"form" :
{
"status" : "true",
"formID" : "form3"
}
} );
var CustomizePPT = new Object();
CustomizePPT.setHiddenFields = function(){
var request = [];
var container = '';
console.log(arguments);
request = arguments[0].hidden;
console.log(arguments[0].hasOwnProperty('form'));
if(arguments[0].hasOwnProperty('form') == true)
{
if(arguments[0].form.status == 'true'){
var parent = document.getElementById("container");
container = document.createElement('form');
parent.appendChild(container);
Object.assign(container, {'id':arguments[0].form.formID});
}
}
else{
container = document.getElementById("container");
}
//var container = document.getElementById("container");
Object.keys(request).forEach(function(elem)
{
if($('#'+elem).length <= 0){
console.log("Hidden Field created");
var input = document.createElement('input');
Object.assign(input, {"type" : "text", "id" : elem, "value" : request[elem]});
container.appendChild(input);
}else{
console.log("Hidden Field Exists and value is below" );
$('#'+elem).val(request[elem]);
}
});
};
CustomizePPT.setHiddenFields( { "hidden" : {'fieldinFORM' : 'thisdata201' , 'fieldinFORM2' : 'this3'}, "form" : {"status" : "true","formID" : "form3"} } );
CustomizePPT.setHiddenFields( { "hidden" : {'withoutFORM' : 'thisdata201','withoutFORM2' : 'this2'}});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id='container'>
</div>