Adding textbox on button click with javascript

2020-03-31 08:22发布

问题:

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/

回答1:

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


回答2:

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