58

How do you create a hidden field in JavaScript into a particular form ?

    <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> 
joe
  • 34,529
  • 29
  • 100
  • 137
  • 4
    Since your script is running before the form exists - what you want is impossible. You could write it in a function and assign it to the onload event though. Your HTML has some errors too, see http://validator.w3.org/ – Quentin Jun 16 '09 at 11:14

5 Answers5

173
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);
annakata
  • 74,572
  • 17
  • 113
  • 180
Haim Evgi
  • 123,187
  • 45
  • 217
  • 223
  • 1
    The forms collection is more appropriate than getElementById for a named form and this all depends on the execution order of the JS vs the DOM loading, but essentially this is the right approach – annakata Jun 16 '09 at 11:17
  • But i just try to use its said the form element is null – joe Jun 16 '09 at 11:33
  • As David pointed out, make sure you are executing this *after* the DOM has loaded. Try using the onload event for starters. – annakata Jun 16 '09 at 11:38
  • at the same point .. document.chells is working but document.getElementById(chells) return null . What would be problem . How to reslove this – joe Jun 16 '09 at 11:49
  • I found the Issue .. Its Difference between name and id – joe Jun 16 '09 at 12:21
  • in the original i wrote this : 'give to form element id attribute what you want' because i see that u have only name – Haim Evgi Jun 16 '09 at 12:55
30

You can use jquery for create element on the fly

$('#form').append('<input type="hidden" name="fieldname" value="fieldvalue" />');

or other way

$('<input>').attr({
    type: 'hidden',
    id: 'fieldId',
    name: 'fieldname'
}).appendTo('form')
Shreeyansh Jain
  • 1,407
  • 15
  • 25
8

I've found this to work:

var element1 = document.createElement("input");
element1.type = "hidden";
element1.value = "10";
element1.name = "a";
document.getElementById("chells").appendChild(element1);
jaybro
  • 1,363
  • 1
  • 12
  • 23
1

insertAdjacentHTML does the trick, and is probably the easiest way, query for the parent, and then just ask to insert before the end, or after the beginning as you see fit, i.e:

document.querySelector('#chells').insertAdjacentHTML('beforeend',
  "<input type='hidden' name='status' value='true' />")
Nimrod
  • 392
  • 2
  • 9
  • 2
    Please read [How do I write a good answer?](https://stackoverflow.com/help/how-to-answer). While this code block may answer the OP's question, this answer would be much more useful if you explain how this code is different from the code in the question, what you've changed, why you've changed it and why that solves the problem without introducing others. – Saeed Zhiany Jul 26 '22 at 03:12
0

You can use this method to create hidden text field with/without form. If you need form just pass form with object status = true.

You can also add multiple hidden fields. Use this way:

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>
SivolcC
  • 3,258
  • 2
  • 14
  • 32