How to add / remove textbox dynamically with jQuery

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


<html>
<head>
<title>jQuery add / remove textbox example</title>
 
<script type="text/javascript" src="jquery-1.3.2.min.js"></script>

<style type="text/css">
	div{
		padding:8px;
	}
</style>

</head>

<body>

<h1>jQuery add / remove textbox example</h1>

<script type="text/javascript">

$(document).ready(function(){

    var counter = 2;
		
    $("#addButton").click(function () {
				
	if(counter>10){
            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="" >');
            
	newTextBoxDiv.appendTo("#TextBoxesGroup");

				
	counter++;
     });

     $("#removeButton").click(function () {
	if(counter==1){
          alert("No more textbox to remove");
          return false;
       }   
        
	counter--;
			
        $("#TextBoxDiv" + counter).remove();
			
     });
		
     $("#getButtonValue").click(function () {
		
	var msg = '';
	for(i=1; i<counter; i++){
   	  msg += "\n Textbox #" + i + " : " + $('#textbox' + i).val();
	}
    	  alert(msg);
     });
  });
</script>
</head><body>

<div id='TextBoxesGroup'>
	<div id="TextBoxDiv1">
		<label>Textbox #1 : </label><input type='textbox' id='textbox1' >
	</div>
</div>
<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'>

</body>
</html>

107 comments on “How to add / remove textbox dynamically with jQuery

  1. How can I get the value of randomly generated text box value in spring mvc

    Reply
  2. Thanks for sharing.. Can you suggest me how to insert data in node.js using add remove input field

    Reply
  3. Great tutorial… Easy to understand & learn.
    Can you share How to insert multiple data in PHP using add remove input field in jquery

    Reply
  4. how would I do it if I want to display the text boxes, that are disabled, and displaying the data from the sql tables. I can connect to db, but how will it work as they rows in the table will be dynamic and for each row I need the textbox

    Reply
  5. Hi,
    thank for this snippet.

    I would like to calculate the fields. Example:

    Textbox # 1: 150
    Textbox # 2: 200

    and retrieve the value of the added fields.

    How to do ? Thank you

    Reply
  6. where do i get this file jquery-1.3.2.min.js ? thank you

    Reply
  7. why its not working in IE and showing -> IE restrict this webpage from running script or ActivX controls.

    Reply
  8. code is not working….Why do you put the code…..

    Reply
  9. i want to open 4 dynamically with using jquery so how can i do that? can you please give me example of that.. i am waiting for your reply..

    Reply
    1. simply write 4 times.. no need of jquery
      and if you wish to include more then link the fourth textbox with the code above

      Reply
    1. send the data via ajax to another page…
      suppose you created a database of name textbox with value id,login,city,textvalue
      thn your code will be like dis…
      ——————— the following part of code given above will be modified like this————————

      $(“#getButtonValue”).click(function () {

      var msg = ”;
      for(i=1; i<counter; i++){
      msg += $('#textbox' + i).val();
      $.post('textvalue.php',{m:msg},function(data){
      });
      }
      alert(msg);
      });
      });

      ———–and the textvalue page will be like dis—————-

      gudluck

      Reply
    2. send the data via ajax to another page…
      suppose you created a database of name textbox with value id,login,city,textvalue
      thn your code will be like dis…
      ——————— the following part of code given above will be modified like this————————

      $(“#getButtonValue”).click(function () {

      var msg = ”;
      for(i=1; i<counter; i++){
      msg += $('#textbox' + i).val();
      $.post('textvalue.php',{m:msg},function(data){
      });
      }
      alert(msg);
      });
      });

      ———–and the textvalue page will be like dis—————-

      gudluck

      Reply
    3. there s a little correction

      send the data via ajax to another page…
      suppose you created a database of name textbox with value id,login,city,textvalue
      thn your code will be like dis…
      ——————— the following part of code given above will be modified like this————————

      $(“#getButtonValue”).click(function () {

      var msg = ”;
      for(i=1; i<counter; i++){
      msg = $('#textbox' + i).val(); ————————–correction is in this line where i delete the + with msg———————-
      $.post('textvalue.php',{m:msg},function(data){
      });
      }
      alert(msg);
      });
      });

      ———–and the textvalue page will be like dis—————-

      gudluck

      Reply
  10. thanks for the code, and am using jquery-1.11.1 version its working well while am trying in sample code but i did repeat the code in my real time project, here php not considering appended text box values which means it taking very first text box alone.

    Reply
  11. VERY VERY VERY MEGA ULTRA GIGA HELPFUL,
    I’ve used it to create FILE UPLOAD FIELDS, I also change and removed some JS code and it work like in my dream!
    THANK SO MUCH

    Reply
  12. how we make an xml which store text box value and then show into gridview using jquery

    Reply
  13. Hello Friends. I’m getting the following error in IE8, Please help me to fix this issue urgently.
    Many Thanks in Advance.
    ‘after()’ is null or not an object
    note: The same code is working fine in other browser like chrome,safari etc.

    Reply
  14. Is it possible to always leave the minimum of 1 textbox and an maximum of 8?
    I am trying to create div’s with in there (name, adress, e-mail) and if people want to add a user, then press the button. The problem is if they remove someone (accident for example) Then you will lose the data.

    Can i combine the jQuery with an PHP form? Or does the form don’t registred all the data?

    Reply
  15. code is very nice but its not running in my php page
    any sulotion pleas

    Reply
  16. I have script like this:

    BEGIN

    newTextBoxDiv.after().html(

    ” +

    ‘$input04) { ?>’ +

    ‘<option value="' +

    '’ +

    ‘”>’ +

    ” +

    ” +

    ” +

    ” +

    ‘Jumlah : ‘ +

    ”);

    END

    When I put “$input04) { ?>” and “”, adding another “textfield” and “option select” not working

    Reply
  17. hi sir. can you give the code of computing the value of the record in the text box (“when my record is interger”) .. thanks. 😀

    Reply
  18. HI,

    i tried this solution and it is working fine. however my problem is that i have some more buttons like save and print on the form and when i click on those buttons it causes postback of the page and the TextBoxDiv1 becomes visible and the jquery functions for add and remove buttons stop working after that. i tried byadding return false on other button click but it did not help me out. can you please guide me ?

    Reply
  19. Can somebody help me with my query. I am a newbie for jquery.

    With this code on click of a button I get values in a string. But what If i want values of a textbox in different strings so that I can pass each value in my code to some different list column.

    Thanks

    Reply
  20. Thanks, this is an awesome code. Can you also teach me how to save the values placed on those textbox to database?

    thanks a lot!!!

    Reply
    1. It is really simple. Just add “runat=server” to the textboxes and the “submit” button while creating them dynamically. So the values in the boxes can be fetched using code behind source and insert them in the database.

      Check the below link which has a an article for what you are looking for. It not only creates the textboxes, but also a “submit” button is created dynamically and fetches the values.

      http://www.encodedna.com/2013/07/dynamically-add-remove-textbox-control-using-jquery.htm

      You can modify code the way I have described above.

      Reply
  21. how to add another texbox and get value of both text box when click on gettextbox value pls help!!!!!

    Reply
  22. how to add another texbox and get value of both text box when click on get textbox value button pls help

    Reply
  23. Hi Sir!

    How will i save the textbox value using CI? Thanks!

    Reply
    1. Hi,

      There are two ways you can do it.

      1) Simple “Hide” and “Show” images.

      $(‘#btShow’).click(function() {
      $(‘#imgTest’).show();
      });

      $(‘#btHide’).click(function() {
      $(‘#imgTest’).hide();
      });

      2) Add or remove the images.

      $(‘#btShow’).click(function() {

      var ImgList = new Array();
      ImgList[1] = ‘http://www.encodedna.com/images/utility.png’;
      $(‘#imgTest’).attr(‘src’, ImgList[1]);
      });
      $(‘#btHide’).click(function() {
      //$(‘#imgTest’).hide();

      var imgBlank = ‘http://www.encodedna.com/images/blank.png’;
      $(‘#imgTest’).attr(‘src’, imgBlank);
      });

      Reply
  24. How to Handle validation for this text box? Please give the code for validation

    Reply
  25. sir please give some example struts2 with grid using jquery and struts2 with jquery(like show and hide textfiled when drop down list is use.

    $(document).ready(function() {
    $(‘#types’).change(function(){
    if($(‘#types’).val() == ‘Other’)
    {

    $(‘#other’).show();
    //document.getElementById(‘other’).disabled = true;
    }
    else
    {
    $(‘#other’).hide();
    }
    });
    });

    Registration Page

    but it have no efect of show and hide

    Reply
  26. Hey is it possible to create next textbox when user hits enter button(on the keyboard). Say after giving some input in first textbox if the user hit enter key can we create next textbox. Hope u understood what i meant. By the thank u for u tutorial, is helping a lot.

    Reply
  27. Hi, I tried to retrieve the textbox value in the servlet by using getParameter()
    However, it doesn’t work for the added textboxes (the first one is OK).
    Does anyone know why? and how can I solve this problem?
    Thanks in advance.

    Reply
    1. you store the value in the hidden filed and then separate through thing and store in the database using split

      Reply
  28. dear sir

    how to insert dynamic textbox values into database using jsp or javascript

    Reply
    1. Assuming that you have a button that will handle the submission with attribute id=”submit”:

      // this should be put inside the $(document).ready(function() { ... }); or $(function() { ... });
      $('#submit').click(function() {
          
          //looping through the textboxes 
          for(i=1; i<counter; i++) {
              
              $.post(
                  // Data will be passed to this php file. This will do the server side processing.
                  'process.php', 
                  { 
                      value: $('#textbox'+i).val() // Data (values of textboxes) that will be passed via HTTP POST request.
                  }, 
                  function() { // A callback function that will be executed after a successful request.
                      var msg += "\n Textbox #" + i + " : " + $('#textbox' + i).val();
                      alert(msg);
                  }
              );
          
          }
          
      });
      

      Aldrin.

      Reply
    2. In process.php:

      
      /** Assuming that you will use MySQL for your database **/
      
      $connect = mysql_connect('localhost', 'root', '') or die(mysql_error()); /** database connection **/
      $selectdb = mysql_select_db('dbname', $connect); /** selecting the databse **/
      
      
      Reply
  29. how we will handle these multiple textboxes with php

    Reply
    1. if( isset( $_POST[‘textbox1’] ) ){
      $value1=$_POST[‘textbox1’];}
      else if ( isset( $_POST[‘textbox2’] ) ){
      $value2=$_POST[‘textbox2’];}

      etc….

      Reply
      1. //Load textbox values into an array:

        for($i=1;$i<=10;$i+=1)
        {
        if(isset($_POST['textbox'.$i]))
        {
        $textboxes[$i]=$_POST['textbox'.$i];
        }
        }

        Reply
  30. Can someone just post the full code that works in the latest jquery. Mine wont work. No errors, just the buttons wont work

    Reply
    1. it should work on chrome,mozila ,opera and safari the above code. the only browser that doesn’t work is IE

      Reply
  31. For version after 1.4 ,there is another way apart from removing after() object ,

    that is adding “” include after()

    Reply
  32. Nice code, however I did notice your example has 2 and tags.

    Also, for those who want to use this code on jquery v1.7+ find this:
    newTextBoxDiv.after().html(‘Textbox #’+ counter + ‘ : ‘ +

    and replace with:
    newTextBoxDiv.html(‘Textbox #’+ counter + ‘ : ‘ +

    Cheers!

    B

    Reply
    1. Thanxs for your comment i was fighting with the error since 2 days ur awesome dude @Boris

      Reply
  33. Solutions do not work with jquery 1.7.1.

    Any suggestion to update the code ?

    Thx

    Reply
    1. Finally, the code works fine under jquery 1.7.1 without .after() and jQuery.noconflict()

      Reply
  34. This is Very Good JQuery for adding New Field.
    Very Nice………..

    Reply
    1. it should work on chrome,mozila ,opera and safari the above code. the only browser that doesn’t work is IE

      Reply
  35. How would i add css and style to the textboxes that are added dynamicaly?

    Reply
  36. Working great but can someone show me how to get the msg variable into my php script?

    Reply
  37. WOW THIS IS AWESOME! just what i’ve been looking for.
    Whew save me a lot of time 🙂
    anyways..
    can you please do a tutorial on how to save the fields value in php/mysql.
    Please 🙂
    i’ll wait for your response.

    Reply
    1. all of a sudden it’s not working on localhost? I need this.

      Reply
  38. thanks nice work 🙂 may I know how do I send it to other php page via POST? I’m a new PHP learner and I don’t know much about javascript.

    Thanks in advance 🙂

    Reply
  39. Nice coding it’s working 100%,,

    I have a small problem, i’m looking for a update for my site..

    BOX –> value

    (BOX)Length | (BOX)Height | (BOX)Base –> Add |Delete

    want to add or delete and these box value should be calculate… have u any idea..

    thanks
    Buewanesh

    Reply
  40. Its working. just remove the “.after()” then it will work for jquery-1.4.4.min.js too.
    Thanks!

    Reply
  41. The code works great with Jquery 1.3.x but is not working with 1.4.2 it reports an error as follows:
    Error: newTextBoxDiv.after() is undefined

    Im not so much experience using jquery, so i cannot help as i would like. But, let me say, this code is great

    Greetings

    Reply
    1. I was able to get it to work with jQuery 1.4.2 by removing the “.after()” and using newTextBoxDiv.html(‘<label…) instead of newTextBoxDiv.after().html('<label…). So far everything appears to be working just fine in 1.4.2 with the ".after()" removed

      Reply
      1. thanks for this fix, had me stumped for half an hour before i decided to hit google 🙂

        Reply
  42. This code is not working with latest version of jQuery (current version is 1.4.2). Can someone correct code so it’s working with latest version of jQuery

    Reply
  43. Hi,
    How do i bind this textbox to a piece of data from database and where.
    Please suggest.
    Thanks

    Reply
  44. I m glad It works easily and very accurate.Good Job..

    Reply
    1. read the first reply 😉

      i was looking for something like this.
      i could creat dynamically forms but i couldn’t get the valeus. Nice code, thx 🙂

      Reply

Leave a Comment

Your email address will not be published. Required fields are marked *