Connecting Tech Pros Worldwide Help | Site Map

add input textbox between field in a form

Member
 
Join Date: Sep 2007
Posts: 77
#1: Nov 20 '08
My code below, I can add and remove textbox, however, it can add/remove the
last one only.

How I can add a input textbox between field?

thanks.

my html file
Expand|Select|Wrap|Line Numbers
  1. <script type="text/javascript" src="addHTMLControls.js"></script>
  2. <a href="javascript:addInput()">Add more input field(s)</a><br>
  3. <a href="javascript:deleteInput()">Remove field(s)</a>
my .js file
Expand|Select|Wrap|Line Numbers
  1. var arrInput = new Array(0);
  2.   var arrInputValue = new Array(0);
  3.  
  4. function addInput() {
  5.   arrInput.push(arrInput.length);
  6.   arrInputValue.push("");
  7.   display();
  8. }
  9.  
  10. function display() {
  11.   document.getElementById('parah').innerHTML="";
  12.   for (intI=0;intI<arrInput.length;intI++) {
  13.     document.getElementById('parah').innerHTML+=createInput(arrInput[intI], arrInputValue[intI]);
  14.   }
  15. }
  16.  
  17. function saveValue(intId,strValue) {
  18.   arrInputValue[intId]=strValue;
  19. }  
  20.  
  21. function createInput(id,value) {
  22.   return "<input type='text' id='test "+ id +"' onChange='javascript:saveValue("+ id +",this.value)' value='"+ value +"'><br>";
  23. }
  24.  
  25. function deleteInput() {
  26.   if (arrInput.length > 0) { 
  27.      arrInput.pop(); 
  28.      arrInputValue.pop();
  29.   }
  30.   display(); 
  31. }
RamananKalirajan's Avatar
Needs Regular Fix
 
Join Date: Mar 2008
Location: Chennai - India
Posts: 348
#2: Nov 20 '08

re: add input textbox between field in a form


Hi, it seems to be u are maintaining a stack inorder to add or remove the input text field in the form. Can u please explain what u are trying to do. Do You want to add the field randomly inside the form

Regards
Ramanan Kalirajan
acoder's Avatar
Site Moderator
 
Join Date: Nov 2006
Location: UK
Posts: 14,581
#3: Nov 20 '08

re: add input textbox between field in a form


Quote:

Originally Posted by perhapscwk

My code below, I can add and remove textbox, however, it can add/remove the
last one only.

How I can add a input textbox between field?

The code is horribly inefficient in that it recreates everything again. Surely, it'd be better to only add/delete what you need. It would, however, require more or less a complete rewrite. Are you prepared to do that?

The main problems are the push/pop - they only affect the last array item. You need to use the index of the array to affect other items or use splice() to add items.
Reply