?
Solved

Add remove HTML elements with Javascript

Posted on 2008-11-19
9
Medium Priority
?
1,603 Views
Last Modified: 2012-05-05
I have the following code that i have mostly written and gathered from tutorials, the removing of elements is fine.

The problem occurs when i try to add an element after removing a few of the elements, if i try to add an element it also adds all the elements that were removed.
<html>
<head>
     <title>Test Page</title>
 
     <script language="JavaScript" type="text/javascript">
 
 //CODE FOR INPUTTING FIELDS
     
 var arrInput = new Array(0);
  var arrInputValue = new Array(0);
 
function addInput() {
  arrInput.push(arrInput.length);
  arrInputValue.push("");
  display();
}
 
function display() {
  document.getElementById('parent').innerHTML="";
  for (intI=0;intI<arrInput.length;intI++) {
    document.getElementById('parent').innerHTML+=createInput(arrInput[intI], arrInputValue[intI]);
  }
}
 
function saveValue(intId,strValue) {
  arrInputValue[intId]=strValue;
}  
 
//Add the input
 
function createInput(id,value) {
  return '<div id="child'+id+'"><input type="text" id="test'+id+'" value="'+value+'">test'+id+'<input type="button" value="Remove this element" onClick="removeElement(\'parent\',\'child'+id+'\');"><div>'; 
  
 
}
 
 
 
//Remove the input  
		  
		  
function removeElement(parentDiv, childDiv){     
          var child = document.getElementById(childDiv);
          var parent = document.getElementById(parentDiv);
          parent.removeChild(child);
   
} 
  
     </script>
</head>
 
<body>
    
 
<a href="javascript:addInput()">Add more input field(s)</a><br>
<a href="javascript:deleteInput()">Remove field(s)</a>
<div id="parent">
 
 
</div>
 
 
 
</body>
</html>

Open in new window

0
Comment
Question by:agulaid
  • 4
  • 4
9 Comments
 
LVL 14

Expert Comment

by:jjardine
ID: 22996970
your add function adds the item to the array but then your deleteInput function never removes the data from the array.  So you keep building the array and putting all its contents on the page but never pop the items from the array when they are removed.
0
 

Author Comment

by:agulaid
ID: 22997001
how would i pop the items from the array? im not too familier with the pop function... can you give me an example?
0
 

Author Comment

by:agulaid
ID: 22997015
Im assuming its something like this:


function deleteInput() {
  if (arrInput.length > 0) { 
     arrInput.pop(); 
     arrInputValue.pop();
  }
  display(); 
}

Open in new window

0
What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

 
LVL 82

Expert Comment

by:hielo
ID: 22997119
why do you keep repopulating the entire div? If you add a field, put data in the field and then click add again, the data of the first would be gone - isn't it?
0
 
LVL 82

Expert Comment

by:hielo
ID: 22997401
try:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
 "http://www.w3.org/TR/html4/loose.dtd">
 
<html>
<head>
<title></title>
<script type="text/javascript">
function addField(prop){
	var parentElem = document.getElementById(prop.container);
	if( parentElem )
	{
		var d = document.createElement("div");
		d.innerHTML="<input type='#TYPE#' name='#NAME#' value='#VALUE#' id='#ID#' /><input type='button' onclick='removeField(this.parentNode)' value='Remove' />";
 
		parentElem.appendChild(d);
		for(var p in prop)
		{
			var t = String(p).toUpperCase()
			switch( t ){
				case "TYPE":
				case "NAME":
				case "ID":
				case "VALUE":
				d.innerHTML=d.innerHTML.replace("#"+t+"#",prop[p]);
 
				break;
			}
		}
 
 
		if(prop.id=='auto')
		{
			var limit = parentElem.childNodes.length;
			for( var i=0; i < limit; ++i)
			{
				parentElem.childNodes[i].firstChild.id=prop.name+(1+i);
			}
		}
	return d;
	}
return null;
}
 
function removeField( o ){
	o.parentNode.removeChild(o);
}
</script>
</head>
<body>
<span onclick="addField( {container:'containerDiv',type:'text', name:'test', id:'auto', value:''} )">Add</span>
<div id="containerDiv"></div>
</body>
</html>

Open in new window

0
 

Author Comment

by:agulaid
ID: 22997509
Hielo, the ID isn't unique hence why i did the original loop. your script works well the fields need to be unique and have a looping number.
0
 
LVL 82

Accepted Solution

by:
hielo earned 2000 total points
ID: 22997616
if the fields need to be unique, use:
id:'auto'

try the attached code:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
 "http://www.w3.org/TR/html4/loose.dtd">
 
<html>
<head>
<title></title>
<script type="text/javascript">
function addField(prop){
	var parentElem = document.getElementById(prop.container);
	if( parentElem )
	{
		var d = document.createElement("div");
		var inp="<input type='#TYPE#' name='#NAME#' value='#VALUE#' id='#ID#' /><input type='button' onclick='removeField(this.parentNode)' value='Remove' />";
 
		parentElem.appendChild(d);
		for(var p in prop)
		{
			var t = String(p).toUpperCase()
			switch( t ){
				case "TYPE":
				case "NAME":
				case "ID":
				case "VALUE":
				inp=inp.replace("#"+t+"#",prop[p]);
 
				break;
			}
		}
 
 		d.innerHTML=inp;
 
		if(prop.id=='auto')
		{
			var limit = parentElem.childNodes.length;
			for( var i=0; i < limit; ++i)
			{
				parentElem.childNodes[i].firstChild.id=prop.name+(1+i);
			}
		}
	return d;
	}
return null;
}
 
function removeField( o ){
	o.parentNode.removeChild(o);
}
</script>
</head>
<body>
<span onclick="addField( {container:'containerDiv', type:'text', name:'test', id:'auto', value:''} )">Add</span>
<div id="containerDiv"></div>
</body>
</html>

Open in new window

0
 

Author Comment

by:agulaid
ID: 22997850
Perfect, that works fine... Hielo although i dont understand your code and how it works i will have to make do and use it, how long have you been scripting in Javascript?
0
 
LVL 82

Expert Comment

by:hielo
ID: 22997975
about 5y.
0

Featured Post

Hire Technology Freelancers with Gigs

Work with freelancers specializing in everything from database administration to programming, who have proven themselves as experts in their field. Hire the best, collaborate easily, pay securely, and get projects done right.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Originally, this post was published on Monitis Blog, you can check it here . Websites are getting bigger and more complicated by the day. Video, images and custom fonts are all great for showcasing your product or service. But the price to pay in…
Without even knowing it, most of us are using web applications on a daily basis.  In fact, Gmail and Yahoo email, Twitter, Facebook, and eBay are used by most of us daily—and they are web applications. We generally confuse these web applications to…
In this tutorial viewers will learn how to code links for mobile sites that, once clicked, send a call or text to a specified number. For a telephone link (once clicked, calls a number), begin with a normal "<a href=" link tag. For the href, specify…
The viewer will learn the basics of jQuery including how to code hide show and toggles. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery…
Suggested Courses

809 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question