Blog Image

how to create html element dynamically in javascript

var itemManCnt=2;
function addMoreHomeImage()
{
if(itemManCnt==6)
{
alert(“You can upload only 5 files”);
return false;

}
var parentObj=document.getElementById(‘FileElementItem’);
var divClrBoth = document.createElement(“div”);
divClrBoth.setAttribute(“class”,”ClrBoth”);
divClrBoth.setAttribute(“id”,itemManCnt);

var divClrSelect = document.createElement(“div”);
divClrSelect.setAttribute(“class”,”Select”);

var file= document.createElement(“input”);
file.setAttribute(“type”,”file”);
file.setAttribute(“id”,”InsuranceHomeImage”+itemManCnt);
file.setAttribute(“name”,”InsuranceHomeImage”+itemManCnt);
divClrSelect.appendChild(file);

var divRemove= document.createElement(“div”);
divRemove.setAttribute(“class”,”AddNew”);

var divRemoveLink = document.createElement(“a”);
divRemoveLink.setAttribute(‘onclick’,’deleteHomeImage(‘+itemManCnt+’)’);itemManCnt++;
divRemoveLink.innerHTML=’Remove’;
divRemove.appendChild(divRemoveLink);

divClrBoth.appendChild(divClrSelect);
divClrBoth.appendChild(divRemove);

parentObj.appendChild(divClrBoth);
}
function deleteHomeImage(iEle)
{
var parentObj=document.getElementById(‘FileElementItem’);
var olddiv = document.getElementById(iEle);
–itemManCnt;
parentObj.removeChild(olddiv);
}

Implementation example

<div id=”FileElementItem” class=”FileElement”>
<div class=”ClrBoth”>
<div class=”Select”>
<input type=”file” name=”InsuranceHomeImage1″ id=”InsuranceHomeImage1″>
</div>
<div class=”AddNew”>
<a onclick=”addMoreHomeImage()”>Add New</a>
</div>
</div>
</div>



Author: admin

Vinod Ram has been in Software Industry since 2006 and has experience of over 16 years in Software Development & Project Management domain specialised majorly in LAMP stack & Open Source Technology, building enterprise level Web based Application, Large Database driven and huge traffic Websites and Project Management. He loves to write information articles and blog to share his knowledge and experience with the outside world and help people to find solution for their problems.