How To Add A Form TextBox With JQuery

Last week, I was playing around with building a Polling app. I looked at how PollEverywhere does the poll adding part, and was really inspired by how a new poll box is created when the user starts typing in a question. I’m pretty new to JQuery, so I was really proud to replicate the functionality in my app, which you can play with right here (start typing a question and see a new question text box pop up!). Here is how I did it:


You can also find this code on Github.

$(function() { //The code only loads "on document ready", when the HTML is loaded. 
	var numFields = 0; //keeps track of the number in the question's id and name
	function appendHandlerToFields(){ //Adds a listener to each new field, which listens for the user to type something. 
               
		$('#poll_questions_attributes_' + numFields + '_text').keypress(function() {
				addField(); //when the user types something, a field is added
		});
	};

	function addField(){
                //stops listening for the user typing something from the previous question field
		$('#poll_questions_attributes_' + numFields + '_text').unbind('keypress'); 
		numFields ++; //increments the field number
		var id = 'poll_questions_attributes_' + numFields + '_text'; // unique id for the new question which will be added
		var name = 'poll[questions_attributes][' + numFields +']'; //unique name for the new question which will be added
		$('<br /><input id=' + id + ' name=' + name + ' size="30" type="text">').insertAfter('#poll_questions_attributes_' + (numFields - 1) + '_text'); //inserting the new question field after the previous question
		appendHandlerToFields(); //adds a listener for the user to start typing in the newly added field
	};

	appendHandlerToFields();
});

Enjoy the article? Join over 14,500+ Swift developers and enthusiasts who get my weekly updates.