jQuery Dynamically Add Form Elements

Sam Deering
Share

How to dynamically add form elements using jQuery/JavaScript. This is useful when the DOM has already loaded and you need to add an extra input field say, based upon a users action or selection. You can create any new form elements not just input fields. As an alternative you could also create the inputs in the page and simply hide them and then show them when they are required.

Example: Insert a new input box called “password2” after one called “password1” when password1 is changed.

//change event on password1 field to prompt new input
$('#password1').change(function() {
		//dynamically create new input and insert after password1
		$("#password1").append("");
});