Today i will show you how to add a new text input field on button click using jQuery.

This functionality is useful if you have a form and you want to ask information where you want the user to have control how many information they want to provide.

First, We will add a button to the form. Let’s use an anchor tag as our button and just add some styling to it to make it look like a button (Please see the demo).

	<input type="text" name="textbox[]" />
	<a class="button add-input">Add Textbox</a>

Try it yourself →

As you can see, it is just a normal form.

After that, we will handle the click event of the button using jQuery. Once the button is clicked, using the insertAfter() method, we will insert a new input tag after the last text input. We can get the last text input by supplying the total number of text inputs minus 1 into the input:eq() selector. Then, we will add a focus to the newly added text input using the focus() method.

$('.add-input').click(function(e) {
	var text_input = $('form input[type=text]');
	$('<input type="text" name="textbox[]" />').insertAfter('form input[type=text]:eq('+(text_input.length - 1)+')').focus();

Try it yourself →

See the demo to see this tutorial in action.