Matt
Matt

Reputation: 171

adding inputs to html form, using javascript

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!

Upvotes: 1

Views: 5347

Answers (3)

David Hedlund
David Hedlund

Reputation: 129782

Gve the form an id

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

Create the JavaScript 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.)

Upvotes: 2

Traveling Tech Guy
Traveling Tech Guy

Reputation: 27811

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);

Upvotes: 2

Dumb Guy
Dumb Guy

Reputation: 3446

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.

Upvotes: 3

Related Questions