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!
This is because you are appending the elements to the body, which means that
insertBeforecannot findelement(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 thebody, 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.