I would like to have an Add another field button that creates a text field <input type="text" name="pet"> each time that button is pressed.
I currently have this code:
<html>
<head>
<script>
function add_field()
{
document.write( '<input type="text" name="pet">' );
};
</script>
</head>
<body>
<form name="input" method="get">
Favourite pets:<br>
<input type="text" name="pet">
<button type="button" onclick="add_field()">Add another field</button><br>
<input type="submit" value="Submit"><br>
</form>
</body>
</html>
But when I press the Add another field button I just get a page with only a text field, all my other content disappears. How do I still keep my other html content while adding another text field?
This line:
Will replace the entire document with the inserted markup. If you want to append the input field, you need to find the form you want to append to, create the input field and append it. Try something like:
This will insert the
inputin the end of the form. You can use other methods, such asinsertBeforeto place the input field where you want it.Or use jQuery.