tags:

views:

444

answers:

1

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>
+3  A: 
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);
Haim Evgi
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
But i just try to use its said the form element is null
joe
As David pointed out, make sure you are executing this *after* the DOM has loaded. Try using the onload event for starters.
annakata
at the same point .. document.chells is working but document.getElementById(chells) return null . What would be problem . How to reslove this
joe
I found the Issue .. Its Difference between name and id
joe
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