views:

224

answers:

3

Hello. I have an html form that I would like to add inputs fields to using javascript. Originally I had the input fields by themselves underneath the 'body', and the following was able to add the fields:

   // Create number input field
   var phoneInput = document.createElement("INPUT");
   phoneInput.id = "phone" + instance;
   phoneInput.name = "phone" + instance;
   phoneInput.type = "text";

   // Insert that stuff
   document.body.insertBefore(document.createElement("BR"), element);
   document.body.insertBefore(phoneLabel, element);
   document.body.insertBefore(phoneInput, element);

I then added a 'form' element around the original inputs in the html file.

    <body>
 <form action=searchform.php method=GET>
  <LABEL for="phone1">Cell #: </LABEL>
  <input id="phone1" type="text" name="phone1">
  <input type="button" id="btnAdd" value="New text box" onclick="newTextBox(this);" />
 </form>
    </body>

Now the button doesn't add new text boxes. Have I structured this incorrectly? Thanks!

A: 

This is because you are appending the elements to the body, which means that insertBefore cannot find element (because it's in the <form>, not the <body>), so it never gets inserted.

A quick way to fix this would be to use document.body.firstChild.insertBefore. However, if the form is no longer the first element in the body, this will no longer work.

A cleaner, better way would be to give your form an ID (e.g. <form id="myform">), and then access the form using: document.getElementById("myform").insertBefore. Then you can place your form anywhere, and it will still be accessible using the ID.

Dumb Guy
hmmm, incase the body had a lot more children, is there a way I could label the form with an id, and then have the insertBefore point to that? Thanks.
Matt
didn't see the rest of the response. Thanks man!
Matt
You're welcome!
Dumb Guy
A: 

give the form an id

<form id="myForm" action="searchform.php" method="GET">

create the javacript elements just as you used to, then you can just add the elements like so:

var f = document.getElementById('myForm');
f.appendChild(document.createElement('br'));
f.appendChild(phoneLabel);
f.appendChild(phoneInput);

(insertbefore would work on f as well, although i think this is more readable)

David Hedlund
A: 

Easiest would be to use jQuery. Add an ID to your form, for easier reference:

<form id="myform" action="action" method="GET">
  <input type="hidden" name="a" value="1"/>
  <input type="hidden" name="b" value="2"/>
</form>

<script type="text/javascript">
  $("#myform").append('<input type="hidden" name="c" value="3"/>');
</script>

You can later change the value of your new input, by easily referring to it:

$("#myform input[name='c']").val(7);
Traveling Tech Guy