Dynamically Add Textbox to Site
This tutorial will show you how to program a button that will add textboxes to your site without having to reload the page that you are one. To do this we will be using JavaScript. The code to do this is actually simple, and I will explain every little detail of it so you can understand how it works. Let’s get started on the code.
<html> <head> <title>Add Items To Invoice</title>
We start with our basic HTML tags to start a website.
<script language="javascript"> row_no=0;
Next, we declare that we are going to start a script and tell the browser what type and then we set a variable for us to use so we know how many boxes have been added by the user.
function addRow(tbl,row){
row_no++;
if (row_no<=20){
Next we declare our function. A function is a set of code that is run every time you call it. You inject variables to it for it to use based on input from the user or the html file. Everything from here until you see the tag is run every time we call this function in the HTML part of the document but only if the button hasn’t been pressed 20 times.
if (row_no<=20){
if (row_no>=10){
var textbox = row_no+'.)<input type="text" size = "2" maxlength= "2" name= quantity[]>';}
if (row_no<10){
var textbox = row_no+'. )<input type="text" size = "2" maxlength= "2" name= quantity[]>';}
var textbox2 = '<input type="text" size = "95" maxlength= "100" name= desc[]>';
var textbox3 = '<input type="text" size = "20" maxlength= "20" name= itemno[]>';
var textbox4 = '<input type="text" size = "6" maxlength= "6" name= ourcost[]>';
var textbox5 = '<input type="text" size = "6" maxlength= "6" name= cost[]>';
var textbox6 = '<input type="text" size = "3" maxlength= "3" name= distid[]>';
These lines declare the textboxes that will be added every time the button is clicked. The sample I am using here is for an invoice creation system. The user would click the button every time they needed to add a line (item) to the invoice. These lines are actually setting the JavaScript variables equal to the text (which in this case is HTML code). Notice the first line is controlled by an IF statement. This is so that the numbers line up. Without it the number that are double digit (greater than 9) wouldn't be in line with the single digit numbers. Notice that the names of the boxes include brackets, which makes them an array. Every box that has that name will go to the same variable and allow us to call it when we receive this data.
var tbl = document.getElementById(tbl); var rowIndex = document.getElementById(row).value; var newRow = tbl.insertRow(row_no);
The first two lines here retrieve the information for the table and the current row of the table from the browser so the script knows where to put the textboxes. The third line create a new row in the table using the variable we declared earlier (which is currently 1).
var newCell = newRow.insertCell(0); newCell.innerHTML = textbox;
These 2 lines of code simply create a cell in that row and inject the html of the variable that we declared into that cell which will intern display a textbox in that cell.
var newCell = newRow.insertCell(1); newCell.innerHTML = textbox2; var newCell = newRow.insertCell(2); newCell.innerHTML = textbox3; var newCell = newRow.insertCell(3); newCell.innerHTML = textbox4; var newCell = newRow.insertCell(4); newCell.innerHTML = textbox5; var newCell = newRow.insertCell(5); newCell.innerHTML = textbox6;
We repeat this process for the other 5 boxes we will be inserting each time the button is pressed.
}
if (row_no>20){
alert ("Too Many Items. Limit of 20.");
}
}
First we create the if statement. Next we create another if to see if the variable is greater than 20. If it is, show an alert telling the user that the limit has been reached. Then we close the If, and finally close the function.
</script> </head> <body>
Now we end the script and head and start the body of the HTML file.
<form name="invoice" method="post" action="insert.php">
Invoice #: <input type="text" size = "6" maxlength= "6" name="invoice" />
<input type="submit" value="Add Invoice">
<input type="button" name="Button" value="Add Item to Invoice" onClick="addRow('table1','row1')">
<table width="1000" border="0" cellspacing="0" cellpadding="2" id="table1">
<th><center>QTY</th>
<th>Item Description</th>
<th>Item #</th>
<th>OurCost</th>
<th>Cost</th>
<th>DistID</th></center>
<tr id="row1">
</tr>
</table>
First, we set up the form so that we can submit the values once they have been added. Then we add a textbox for the user to put in the invoce number that we are creating. (We will use this value when we collect this data to insert into the database). Next we create the button that will allow the user to add the items to the invoice and then the button to submit the values to the insert.php file. Notice the "onClick="addRow('table1','row1')" that is on the add item to invoice button. This calls the function we created and inserts the values in parenthesis into the arguments for the function. Then we create our table that these values will be injected into. Then we set up the heading of the tables so the users will know which boxes do what. Then we create the first row so the script will know where to start.
</form> </body> </html>
Then we close our form, body, and HTML. This complete the file.
This is what the site should look like when you go to it.
This is what should appear once you click the button to add an item.
You can continue to add items until you reach the limit (which we made 20) and then you will receive the above message. We will cover how to grab these values on the next page and insert them into the database in a future tutorial. I hope this was easy to follow and thanks for reading.
Popularity: 18% [?]












on June 30th, 2008 at 12:02 am
[...] will be working with PHP and MySQL to insert the data that was inserted into the text boxes on the Dynamically Add Textbox to Site tutorial. We will collect the data and insert the values into a database. To start we need to make sure our [...]
on July 14th, 2008 at 2:03 am
hi,
can u put the full code in a html page. This is bit confusing
on July 27th, 2008 at 11:53 am
Hi
Can you please tell me how to get the dynamically generated textbox values into a JSP. I used getParaneter to get them but its throwing null.
I am new to javascript and jsp. Can you please help me out?
Thanks in advance
Praveen
on August 15th, 2008 at 10:29 am
Земля, земельные участки в Испании
Компания является одной из ведущих риэлтерских агентств Испании (жилищная недвижимость, коммерческая недвижимость
Компания действительный член Российской гильдии риэлтеров, Испании ассоциации риэлтеров.
Профессиональная деятельность агентства недвижимости застрахована
Много принципов работы, а также технология, в работе с клиентами применяемые нами стали новаторскими для нашего города
on September 1st, 2008 at 1:56 am
Hello!,
on September 1st, 2008 at 1:57 am
Good day!,
on September 1st, 2008 at 3:41 am
Hi!,
on September 4th, 2008 at 6:07 pm
Can we add a Group(several different input types…Text Box..Drop Down..etc) dynamically.?
Also can it be nested, for example.
Company DataBase, i wish to add multiple location with multiple telephone numbers.
Hence I want ADD New telephone(similar to your example) & then add new location would then ADD full set along with ADD New Telephone.
Could you please guide, whether this would be possible.?
on September 7th, 2008 at 7:31 am
Hello,
Can i add following DropDown in the above JScript Code.?
<option value=”"> 0) { mysql_data_seek($countries, 0);$row_countries = mysql_fetch_assoc($countries); } ?>
If No, how do i do it.?
Thanks in Advance
Manish
on September 7th, 2008 at 7:32 am
<option value=”"> 0) { mysql_data_seek($countries, 0);$row_countries = mysql_fetch_assoc($countries); } ?>
on September 9th, 2008 at 12:06 pm
[...] every little detail of it so you can understand how it works. Let’s get started on the code. view plaincopy to [...]
on September 9th, 2008 at 12:11 pm
[...] will be working with PHP and MySQL to insert the data that was inserted into the text boxes on the Dynamically Add Textbox to Site tutorial. We will collect the data and insert the values into a database. To start we need to make sure our [...]
on September 19th, 2008 at 4:37 am
Thank u for ur comments which u sent
on September 23rd, 2008 at 5:31 am
Спасибо автору.
on October 18th, 2008 at 7:33 am
Оценка 5!
on October 31st, 2008 at 10:24 pm
супер оригинально
on November 1st, 2008 at 8:31 pm
С чистым юмором.
on November 1st, 2008 at 8:35 pm
hi, could you site some example code on inserting records into mysqlDB using php… i can’t picture it out. tnx
on November 2nd, 2008 at 8:35 pm
класс)мне понра)особенно!
on November 2nd, 2008 at 9:48 pm
“этот вне конкуренции”
on November 3rd, 2008 at 11:23 am
Видела…видела….слишком всё утрировано, но круто)))
on November 3rd, 2008 at 9:06 pm
“Работай с умом, а не до ночи”
on November 3rd, 2008 at 11:17 pm
“отличный блог! отличные посты”
on November 4th, 2008 at 7:16 pm
“Интересная заметка”
on November 5th, 2008 at 12:50 am
“Ты один из немногих, кто действительно хорошо пишет”
on November 5th, 2008 at 7:32 pm
“да, новость пошла по инету и распространяется со старшной силой”
on November 6th, 2008 at 9:28 pm
Хороший пост! Подчерпнул для себя много нового и интересного!
Пойду ссылку другу дам в аське
on November 7th, 2008 at 1:44 am
“Мне очень помогали ваши записи”
on November 7th, 2008 at 3:20 pm
Большое спасибо! Есть ещё повод получить удовольствие… С вашего разрешения, беру.
on November 7th, 2008 at 4:43 pm
Напомнили….Точно, все так.
on November 10th, 2008 at 6:56 am
Hey Dude this is good but is bit confusing , can u please put the whole code in a single file..
on November 16th, 2008 at 1:13 am
Why I Cannot Add Item Invoice, is someting wrong?
on November 16th, 2008 at 5:40 pm
прикона)
on November 24th, 2008 at 11:34 am
Суперский рассказ и автор молодец!
on December 1st, 2008 at 1:03 am
Спасибо огромное!
on January 29th, 2009 at 11:51 am
i’m must use it!
on February 6th, 2009 at 2:17 pm
Суперский рассказ и автор молодец!
on February 9th, 2009 at 5:33 am
Суперский рассказ и автор молодец!
on February 12th, 2009 at 8:59 am
Суперский рассказ и автор молодец!
on March 7th, 2009 at 1:39 am
Hi,
After insert, how can i retrieve data to this dynamic page and edit it?
thanks you
on March 16th, 2009 at 6:01 am
Создание музыки
on March 17th, 2009 at 12:33 am
Компания УралДерево – продажа бруса, а так же лес, пиломатериалы, вагонка, дрова, брус, доска, опил по Свердловской области
on March 18th, 2009 at 3:20 pm
Фирма Экспресс-Ремонт – оказывает ремонт помещений Екатеринбург
on March 18th, 2009 at 8:26 pm
бесплатный софт игр и музыка
on March 19th, 2009 at 5:31 am
best is
http://www.dynamicdrive.com/forums/showthread.php?t=39234
on March 19th, 2009 at 5:32 am
1) Dynamically Add Any Number of Textbox
2) esy to use
3) DESCRIPTION: This javascript code is used to add textbox element dynamically in page or form. You need to call one function “addTextBox()”. Its a easy to modify this script as per your requirement.
4) CODE:
———————
Dynamic Textbox/title>
// ——————————————————–
// Author : Daxa
// Website : http://www.beyondmart.com/
// ——————————————————–
var inival=0; // Initialise starting element number
// Call this function to add textbox
function addTextBox()
{
var newArea = add_New_Element();
var htcontents = “”;
document.getElementById(newArea).innerHTML = htcontents; // You can any other elements in place of ‘htcontents’
}
function add_New_Element() {
inival=inival+1; // Increment element number by 1
var ni = document.getElementById(’area’);
var newdiv = document.createElement(’div’); // Create dynamic element
var divIdName = ‘my’+inival+’Div’;
newdiv.setAttribute(’id’,divIdName);
ni.appendChild(newdiv);
return divIdName;
}
Add New Text Box
on March 25th, 2009 at 8:29 am
Здравствуйте, хочу продемонстрировать на вашем каталоге собственный сайт! Он посвящен медицине! Из него вы засунете в копилку знаний, что сейчас предпринять при: укусах различных паразитов, ожогах (различных степеней а также типов), при оказании первой медицинской помощи а также многое многое другое! Пройти к нему вы можете кликнув по ссылке!!!
on April 10th, 2009 at 9:02 am
Подписался на rss
on April 13th, 2009 at 6:30 am
Пейнтбол в Екатеринбурге и Ревде предоставляет услуги – тактический пейнтбол, а так же проведение спортивных мероприятий
on April 13th, 2009 at 1:23 pm
Бесплатный сайт знакомств для секса, интима и любви : это возможность быстро найти партнера для сексуальных отношений и друга на всю жизнь. На сайте знакомств и общения 24люкс.ру миллионы интим фото девушек и парней. Найди себе подругу или друга для секса и общения. Зарегистрируйтесь, и вам будет доступен мир общения и встреч для секса и развлечений. Сервисы нашей службы знакомств: Эротический Секс-топ 100 девушки и парни с интим фото. Виртуальное общение в чате.
on April 14th, 2009 at 9:51 pm
It’s good, well explained, but limits is a bad idea, never limit the user, what I would do is create an element and add it to the html DOM and then present it when the button is pressed, keeping a count of the number of input boxes there, for later calculations and processing of the data when submitting.
on April 16th, 2009 at 6:57 am
Магазин железных дверей, продажа и установка дверей в Москве и Московской области, металлические двери Россия. Входные железные двери по низким ценам от производителя. У нас большой каталог дверей разных стилей и цветовых гамм. В нашем магазине дверей Вы можете заказать входные стальные двери с ковкой и без. Установка металлических дверей производится по Москве и Московской области.
on April 19th, 2009 at 8:27 am
Thank you author
on April 21st, 2009 at 2:52 pm
Разное
on April 22nd, 2009 at 4:29 pm
Разное
on April 23rd, 2009 at 5:30 am
Разное
on April 23rd, 2009 at 9:26 pm
Разное
on April 24th, 2009 at 7:14 am
Бесплатные компьютерные игры – это самые популярные развлечения в интернете и во всем мире: трудно представить себе человека, для которого ничего не значат слова скачать игры и «games». Их называют по-разному: мини-игры, флеш-игры (flash-игры), онлайн-игры, бесплатные игры. Люди хотят бесплатно играть и развлекаться! Так почему бы не сделать это прямо сейчас? Распространяются файлы игры бесплатно.
on April 24th, 2009 at 11:15 pm
Разное
on April 26th, 2009 at 4:09 pm
Разное
on May 7th, 2009 at 7:21 am
Интернет магазин Ека-Кроха – магазин детской одежды реализует: Катера в Екатеринбурге
on May 12th, 2009 at 9:01 pm
Имидж компании и имидж менеджера
on May 17th, 2009 at 5:20 pm
Разное
on May 18th, 2009 at 6:42 am
Интернет магазин света Svet66 – продажа светильники потолочные, а так же светильники, лампы, торшеры, лампы, люстры, бра по уралу
on May 18th, 2009 at 10:16 am
Разное
on May 18th, 2009 at 8:49 pm
Работаю менеджером. Хочу сделать интернет магазин. Порекомендуйте человека или организацию, кто поможет мне в этом. Главное чтоб человек, который его делает был адекватный и недорого.
on May 20th, 2009 at 8:01 am
Erotic сайтзнакомства для секса, интима и любви : это возможность быстро найти партнера для сексуальных отношений и друга на всю жизнь. На сайте знакомств и общения 24люкс.ру миллионы интим фото девушек и парней. Найди себе подругу или друга для секса и общения. Зарегистрируйтесь, и вам будет доступен мир общения и встреч для секса и развлечений. Сервисы нашей службы знакомств: Эротический Секс-топ 100 девушки и парни с интим фото.
on May 21st, 2009 at 4:42 pm
На нашем сайте Вы можете скачать безмездно мини зрелище супер корова и ещё сотни компьютерных java и hasten games в бесплатном доступе! Воспользуйтесь нашим предложением скачайте компьютерные зрелище весёлая ферма, веселая ферма 2 бесплатно. У нас дозволено найти разнообразные бесплатные онлайн showy (флеш) мини зрелище: стрелялки, гонки, драки, dazzle приколы, развивающие зрелище, аркады, детские зрелище
on May 22nd, 2009 at 2:21 pm
Разное
on May 23rd, 2009 at 2:01 pm
Сайт Сексуальные (sex) знакомства sex-znakomstva.su это интим (интимные, эротические) знакомства для секса приглашает Вас на бесплатный сайт знакомств для секса и любви: секс-знакомства.су – это уникальная возможность быстро найти партнера для интимных, сексуальных отношений и друга на всю жизнь.
on May 25th, 2009 at 7:17 pm
Интересненько, а кто может объяснить девушке как добавить этот блог в избранное?
on May 27th, 2009 at 1:41 pm
Реально удивили и даже порадовали
Никогда не поверил бы, что даже такое бывает
on May 28th, 2009 at 9:40 am
Hello your this code is not working. DO you please give a zip file.
on May 29th, 2009 at 5:39 am
Компания Lim-Company предоставляет услуги – пакеты в Екатеринбурге
on May 31st, 2009 at 6:08 am
Вопрос к автору блога, а вот у вас время у каждой статьи и в комментах пишется… Это какое? Московское? Заранее благодарю за ответ.
on May 31st, 2009 at 1:16 pm
грамотное создание сайтов и услуги копирайтинга
on May 31st, 2009 at 6:03 pm
Фирма Максимал предлагает керамогранит 600х600 в Екатеринбурге
on May 31st, 2009 at 6:23 pm
Фабрика матрешки Матрешкин двор- матрешка чебурашка, классный сувенир. Матрёшка с ушками -панда от производителя оптом г. Сергиев Посад.
on May 31st, 2009 at 7:14 pm
здесь все для свадьбы в Чите
on June 1st, 2009 at 11:19 am
Давольно познавательно. Хочу тоже поделиться нужной ссылкой – фильмы онлайн кино онлайн
on June 5th, 2009 at 3:47 am
А удовольствия должны быть дорогими….
on June 7th, 2009 at 1:56 am
Отличная статья. Дамаю для ваших подписчиков была бы еще полезна статья на тему “номинальный директор стоимость“
on June 24th, 2009 at 5:04 pm
Cool idea. If you have free time, pleas came to my site. Thith is it – How to play spades.
on June 29th, 2009 at 4:54 pm
, ?
!
on July 5th, 2009 at 6:45 pm
gnfdff
on July 14th, 2009 at 4:16 pm
The central subject of this portal is Hi-Tech, games and electronics. Here you will find great number of interesting articles about cell phones and computers, reviews on games and gadgets.
on July 22nd, 2009 at 2:07 am
The Company ExtraPack specializes in manufacturing of plastic, bioplastic and paper shopping bags. Our company is glad to offer you first class offset and flexo printing.
on July 29th, 2009 at 3:59 am
Assist is a leading Bulgarian company specialized in assembly, sales and maintenance of automatic barriers, automatic entrance doors, air-curtains, infrared radiant heating, door mats.
on August 21st, 2009 at 3:08 am
The line if (row_no<=20){ is published two times in your code ,I hope u make the changes.
on September 19th, 2009 at 4:26 pm
The main subject of the web site is steaming and web video. Here you can find great number of useful articles, web video howtos and tutorials and information about video hosting services.
on September 21st, 2009 at 12:27 pm
We are glad to offer you the blog VideoDaddy.info about steaming and video technology. Learn the latest video technology news, read helpful articles and video guides on the portal.
on September 22nd, 2009 at 1:22 am
thanks for the code and it is extremly help for us.
please tel me how to retreive data from particular textbox
on September 26th, 2009 at 9:42 pm
Hi,
When i used ur and tried to view the output, i don’t get the text boxes. I exactly copied the contents given here but it still didn’t work. Could you pls help me out.
Rgds
Vijay
on September 28th, 2009 at 5:30 pm
Discover how our attention to detail complements your Guest Room experience. Hotel Bulgaria suggests the best in service and facilities – a place where luxury resides in every detail; where a flair for elegance provides the uttermost in comfort.
on October 24th, 2009 at 12:31 pm
HotFile Links Search is the first and only tool for HotFile premium users to find what they need. You can submit the HotFile uploads here to get more money and downloads.
on November 9th, 2009 at 4:08 am
Home Cleaning Company provides high quality total care cleaning services – office and house cleaning, window and floor cleaning for commercial and domestic customers in London UK.