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>

About the Author

author image
mkyong
Founder of Mkyong.com, 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.

Comments

Leave a Reply

avatar
newest oldest most voted
daniel
Guest
daniel

how can the inputted values go to
database

vems j
Guest
vems j

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

vems j
Guest
vems j

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

vems j
Guest
vems j

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

Bodry Dexter
Guest
Bodry Dexter

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

VR
Guest
VR

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.

sean
Guest
sean

How To Add / Remove … image ?

arun
Guest
arun
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); });
abiemp
Guest
abiemp

thank you! great works!

Management Quota
Guest
Management Quota

Thnaks very much

Direct admission
Guest
Direct admission

Thanks for sharing sir

abhinav kumar
Guest
abhinav kumar

Thanks for the information sir.

Amit Kumar
Guest
Amit Kumar

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

Dubesh Shrestha
Guest
Dubesh Shrestha

wow… supop!!!! thanks….

Pushpak Khatri
Guest
Pushpak Khatri

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..

vems j
Guest
vems j

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

daniel
Guest
daniel

using webmatrix

sibi
Guest
sibi

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.

Ilyas
Guest
Ilyas

Very Helpful, thank you master.

zeeshan
Guest
zeeshan

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

Keust
Guest
Keust

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?

Zaheer
Guest
Zaheer

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

Turangga
Guest
Turangga

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

mcleen
Guest
mcleen

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

Ravi
Guest
Ravi

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 ?

trackback
How to add textbox dynamically using jquery | Nuwan's Blog
trackback
how do i display dynamic data from database to edit and update it back into database? | BlogoSfera

[…] if you want an example of how the dynamic form fields are added and removed on create page, i worked from this code on this demo page: http://www.mkyong.com/jquery/how-to-add-remove-textbox-dynamically-with-jquery/ […]

Kapil
Guest
Kapil

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

Randz
Guest
Randz

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!!!

arun
Guest
arun

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.

bijol
Guest
bijol

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

bijol
Guest
bijol

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

Archana
Guest
Archana

it helped me a lot

trackback
How to Add Textbox’s dynamically with JQuery | ManjuStudio
Janna
Guest
Janna

Hi Sir!

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

Muthu
Guest
Muthu

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