Tuesday, May 27, 2008

Dynamically Add or Remove HTML elements

<HTML>
<HEAD>
<script type="text/javascript">

var sequence = 0;

function addTextBox()
{
var dynDiv = document.getElementById('dynamicDiv');
var newDiv = document.createElement("DIV");
var newDivIdName = 'Div'+sequence;
newDiv.setAttribute('id',newDivIdName);
var newSpan = document.createElement('SPAN');

addField(newSpan,{ type :"text", name :"test"+sequence, value:"test"+sequence , size:30 });
addField(newSpan,{ type :"button", name :"delete"+sequence, value:"delete", id:"delete"+sequence });

newDiv.appendChild(newSpan);
dynDiv.appendChild(newDiv);

var deleteButton = document.getElementById('delete'+sequence);
deleteButton.onclick=function()
{
removeTextBox(newDivIdName);
}

sequence++;
}



function addField(form,json)
{
var inp=document.createElement("input");
for(var i in json)
{
inp[i]=json[i];
}
form.appendChild(inp);
}


function removeTextBox(divNum)
{
var dynDiv = document.getElementById('dynamicDiv');
var obj = document.getElementById(divNum);
dynDiv.removeChild(obj);
}

</script>

</HEAD>


<BODY>
<form name="testForm">
<div id="dynamicDiv">
<span>

<input type="text" name="address1" value="test"/>
<input type="button" name="Add" value="Add" onclick="addTextBox();" />
</span>
</div>

</form>
</BODY>

</HTML>

No comments: