Adding textbox on button click with javascript

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"> <input type="button" 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.

3

3 Answers

Something like this?

<form name="myForm" onsubmit="return validateForm()"> Pets: <br /> <input type="text" /> <input type="button" 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

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
function add(type) { //Create an input type dynamically. var element = document.createElement("input"); var text = document.getElementById("textId"); //Append the element in page (in span). text.appendChild(element);
}
 h1 { color: #0000ff; }
<h1>KIAAT</h1> <b>Adding textbox on button click with javascript</b> <br><br>
<form> <input placeholder="text" name="element" hidden> </input> <input type="button" value="Click Me" onclick="add(document.forms[0].element.value)"/> <span>&nbsp;</span>
</form>

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like