In jQuery, it’s quite easy to add or remove a textbox dynamically. The idea is quite simple, just combine the use of ‘counter‘ variable, jQuery createElement(), html() and remove() method. See below example :

jQuery dynamic textbox example

<title>jQuery add / remove textbox example</title>
<script type="text/javascript" src="jquery-1.3.2.min.js"></script>
<style type="text/css">
<h1>jQuery add / remove textbox example</h1>
<script type="text/javascript">
    var counter = 2;
    $("#addButton").click(function () {
            alert("Only 10 textboxes allow");
            return false;
	var newTextBoxDiv = $(document.createElement('div'))
	     .attr("id", 'TextBoxDiv' + counter);
	newTextBoxDiv.after().html('<label>Textbox #'+ counter + ' : </label>' +
	      '<input type="text" name="textbox' + counter + 
	      '" id="textbox' + counter + '" value="" >');
     $("#removeButton").click(function () {
          alert("No more textbox to remove");
          return false;
        $("#TextBoxDiv" + counter).remove();
     $("#getButtonValue").click(function () {
	var msg = '';
	for(i=1; i<counter; i++){
   	  msg += "\n Textbox #" + i + " : " + $('#textbox' + i).val();
<div id='TextBoxesGroup'>
	<div id="TextBoxDiv1">
		<label>Textbox #1 : </label><input type='textbox' id='textbox1' >
<input type='button' value='Add Button' id='addButton'>
<input type='button' value='Remove Button' id='removeButton'>
<input type='button' value='Get TextBox Value' id='getButtonValue'>
Tags :
Founder of, love Java and open source stuff. Follow him on Twitter, or befriend him on Facebook or Google Plus. If you like my tutorials, consider make a donation to these charities.
My website is hosted by Liquid Web, I really like their fast and helpful support, it saved me a lot of time. Furthermore, their servers are extremely reliable, fast and stable, I don't remember when was the last time we had server downtime. Btw, they're offering $100 Coupon now, if you are sourcing for great hosting provider, go grab it.

Related Posts

Popular Posts