0
votes

I'm working on a web form with a textbox for pets and an "add pet" button. Each time the button is clicked, an additional textbox should be displayed below the original one.

I'm assuming this would be accomplished with an onclick event, but I can't figure out how to get it to work.

Here is the code I have so far:

    <html>
    <head>
     <title>Project 4</title>
    </head>

    <body>
            <form name="myForm" onsubmit="return validateForm()">
            Pets: <input type="text" id="pets"> 
            <input type="button" id="addPet" value="Add Pet">
            <br>
            </form>
        <script type="text/javascript">
            function makeCopy() {
                var copy = <input type="text">;
                return copy;
            }
        </script>
    </body>
</html>

There are other pieces to this as well, but none of them affect this particular problem I am having so didn't see the need to include the full code as it's fairly long.

Any suggestions are greatly appreciated.

Update: I realize after reading the answers that I should've included more of my code to give you guys a better idea of the actual layout of my page. I have several text fields in my form and need the additional textboxes to be displayed right below the original "pets" textbox. Here's a jfiddle I threw together to give you guys a better idea of the layout. http://jsfiddle.net/a5m8nqwk/

2
Syntax error, var copy = <input type="text">; is bad JavaScript.Sukima
There are several complications on this problem. Namely, adding DOM elements, attaching event handlers, and setting new form element names to be unique and compatible with your server scripts. I'm just letting you know.Sukima
@Sukima, yeah, I mainly just put that in there so there would be something there. It showed the syntax error when I decided to try it just in case.user2932587

2 Answers

3
votes

Something like this?

<form name="myForm" id="myForm" onsubmit="return validateForm()">
    Pets: <br />
    <input type="text" id="pets" />
    <input type="button" id="addPet" value="Add Pet" />
    <br/>
</form>


document.getElementById("addPet").onclick = function() {
    var form = document.getElementById("myForm");
    var input = document.createElement("input");
    input.type = "text";
    var br = document.createElement("br");
    form.appendChild(input);
    form.appendChild(br);
}

Edit: I'd suggest using a table to style the input boxes, keep them in line. FIDDLE

1
votes

You could easily add elements to the DOM:

function createPetField() {
  var input = document.createElement('input');
  input.type = 'text';
  input.name = 'pet[]';
  return input;
}

var form = document.getElementById('myForm');
document.getElementById('addPet').addEventListener('click', function(e) {
  form.appendChild(createPetField());
});